Php hide div by id

Как скрыть элемент на странице

Добрый вечер!
Реально ли скриптом или ещё каким то методом по условию скрыть блок страницы?
Например на сайте есть кнопка или чекбокс, по нажатию будет срабатывать включение/отключения элемента страницы.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
var snowsrc="../images/snow.png"; var no = 20; var log = 0; var hidesnowtime = 0; var snowdistance = "windowheight"; var ie4up = (document.all) ? 1 : 0; var ns6up = (document.getElementById&&!document.all) ? 1 : 0; function iecompattest(){ return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body } var dx, xp, yp; var am, stx, sty; var i, doc_width = 800, doc_height = 600; if (ns6up) { doc_width = self.innerWidth; doc_height = self.innerHeight; } else if (ie4up) { doc_width = iecompattest().clientWidth; doc_height = iecompattest().clientHeight; } dx = new Array(); xp = new Array(); yp = new Array(); am = new Array(); stx = new Array(); sty = new Array(); snowsrc=(snowsrc.indexOf("../images/")!= 1)? "../images/snow.png" : snowsrc for (i = 0; i  no; ++ i)  dx[i] = 0; xp[i] = Math.random()*(doc_width-50); yp[i] = Math.random()*doc_height; am[i] = Math.random()*20; stx[i] = 0.02 + Math.random()/10; sty[i] = 0.7 + Math.random(); if (ie4up else { document.write("\"dot"+ i +"\" style=\"POSITION: fixed; Z-INDEX: "+ i +"; VISIBILITY: visible; TOP: 15px; LEFT: 15px;\">\"0\">\/div>"); } } } function snowIE_NS6() { doc_width = ns6up?window.innerWidth-10 : iecompattest().clientWidth-10; doc_height=(window.innerHeight && snowdistance=="windowheight")? window.innerHeight : (ie4up && snowdistance=="windowheight")? iecompattest().clientHeight : (ie4up && !window.opera && snowdistance=="pageheight")? iecompattest().scrollHeight : iecompattest().offsetHeight; for (i = 0; i  no; ++ i) { yp[i] += sty[i]; if (yp[i] > doc_height-50) { xp[i] = Math.random()*(doc_width-am[i]-30); yp[i] = 0; stx[i] = 0.02 + Math.random()/10; sty[i] = 0.7 + Math.random(); } dx[i] += stx[i]; document.getElementById("dot"+i).style.top=yp[i]+"px"; document.getElementById("dot"+i).style.left=xp[i] + am[i]*Math.sin(dx[i])+"px"; } snowtimer=setTimeout("snowIE_NS6()", 10); } function hidesnow(){ if (window.snowtimer) clearTimeout(snowtimer) for (i=0; ino; i++) document.getElementById("dot"+i).style.visibility="hidden"; } if (ie4up||ns6up){ snowIE_NS6(); if (hidesnowtime>0) setTimeout("hidesnow()", hidesnowtime*1000); } function stopsnow(){ if (log==0){ for (i=0; ino; i++) document.getElementById("dot"+i).style.visibility="hidden"; no = 0; log = 1; document.getElementById('snow-start').innerHTML ='Вкл. снег'; } else { log = 0; no = 20; for (i=0; ino; i++) document.getElementById("dot"+i).style.visibility="visible"; document.getElementById('snow-start').innerHTML ='Выкл. снег'; } }

Источник

Скрытие Div с помощью php

В настоящее время я скрываю div, основанный на выражении if. Метод, который я использую, использует echo out a css стиль display: none Вот что я делаю конкретно:

Мой вопрос: это хороший метод для скрытия div? Возможно ли, что браузер кэширует стиль и поэтому игнорирует стиль echo -ed out css ?

Вы можете просто не включать div вообще. но я не понимаю, что вы имеете в виду в отношении кешируемого стиля.

Встроенные стили кэшируются вместе со страницей, а не в одиночку. Если это хорошо или нет, это зависит от вашего вопроса, и в нем недостаточно информации, чтобы правильно судить об уровне хорошего, который я бы сказал.

. или вы можете дать div только имя класса, которое применяет display: none если вы хотите его скрыть. Или даже встроенный стиль.

@Dagon хорошо вы знаете, как браузер хранит фрагменты html, такие как стиль изображений и т. Д., Чтобы загружать страницу быстрее, если пользователь снова возвращается.

Вот хороший вопрос о динамически генерируемых CSS с плюсами и минусами stackoverflow.com/questions/11853063/…

@VidhuShresthBhatnagar — Браузеры кэшируют изображения и т. Д., Но я никогда не знал, чтобы браузер кэшировал HTML так, как вы, кажется, думаете. Первоначальный комментарий Dagons — это обычный метод, он также чище при просмотре кода, а также быстрее, если в этом div может быть много контента.

6 ответов

Использование Php в CSS (Cascade Style Sheet) не является «правильным»,

Кроме того, вы можете использовать Php в своем HTML:

С помощью этого кода блок div не отображается (и вы не используете его с JavaScript), вы можете использовать это для просто скрытого div:

Мне также нравится первое решение, но я не знаю, как его реализовать . какой будет полный код, который я могу вставить в файл .php, чтобы увидеть его в действии? Это часть (условия), с которой у меня проблема

Почему бы не создать класс:

И чем применить его с PHP:

Как еще вы могли бы скрыть это, кроме использования встроенного стиля? И я тоже считаю, что это не «семантический» класс. Я предположил, что ОП хотел, чтобы div был скрыт и не был удален со страницы, потому что он использовал display:none в вопросе уже display:none . 🙂

Это не лучший способ скрыть div. Поскольку PHP разбирается на стороне сервера, вы можете также включить оператор if или исключить div вместо эхо-значения класса CSS. Единственный раз, когда было бы полезно использовать класс CSS, — если вы планируете использовать JavaScript для отображения div на странице позже, в то время как пользователь находится на самой странице.

Источник

Скрыть div по id в php

Но вот в чем беда, если пользователь решил пройти по какой-то категории, то этот «фильтр» сбрасывается (т.е. ему надо еще раз нажать на кнопку чтобы скрыть ненужные ему категории). Я хотел бы чтобы либо это запоминалось как-то в JS (хотя не могу до этого пока дойти), либо чтобы при нажатии на кнопку пользователю выдавались div’ы с определенным (заранее мною определенным) id.

Задача вроде не трудная, но т.к. знаний у меня — не очень, прошу помощи. МОжет на JS и быстрее, но как сделать чтобы результат запоминался?!(

Скрыть блок div методом PHP
Доброго времени суток, как сделать так что бы при нажатии <input type="button"> скрывался блок <div.

Скрыть div и заменить class
Подскажите пожалуйста как правильно реализовать следующее: Есть такой кусок верстки: <div.

Скрыть div после успешной авторизации
Все привет! В общем имеется код(смотрите ниже). Так вот, как сделать так, чтобы после.

скрыть div, а на его место поставить другой
Помогите пожалуйста. Есть 2 блока #active и #activeout Нужно без помощи javascript сделать так.

1. Использовать куки
либо
2. использовать сесии в PHP
либо
3. использовать БД, записывать в нее то что пользователь скрыл/не скрыл

На php будет быстрее! Он срабатывает быстрее чем js, с js скрываться элементы будут только после загрузки страницы.
Установка кук
http://php.net/manual/ru/function.setcookie.php
В вашем случае всего скорее лучше содержимое куки приготовить примерно в таком виде

// Если найдено вхождение по id if($poisk_v_ctroke) { $close = 'style="display:none'; } else { $close = ''; }

Источник

Hide HTML element (by class or ID) with PHP

In WordPress, is it possible to hide a HTML element by class or ID with php? I’ve used css rule display: none; but this is easily worked around. I have tried the following via functions.php but to no avail:

Basically I need to hide a HTML element for good without anyone being able to alter the code via browser inspector. I’d like to prevent having to create a child theme and mess with templates too.

Would it work if instead of hiding it using display:none or visibility:hidden you just removed the element? This obviously isn’t a practical suggestion if for any reason the page needs that element present to perform any function, but if it’s just something visual that you want to hide permanently so no one can see it, then just remove it using JS.

No, you won’t be able to. Php is not the right tool for this job. Use javascript to remove the whole thing from your html. Or you could use css display: none; to remove your element from the page. FYI, the snippet you provided us with is NOT php, so it won’t work in the functions.php file. I’m actually surprised that you didn’t get any error running it.

@TonyDjukic I could do that through child theme and hooking up a template, however that can cause a lot of issues if the theme is updated and they decide to change things up in that particular template. Is JS reliable? What I mean is if users won’t be able to reverse it via web browser settings? Something like changing CSS via Inspect element.

JS would be reliable because it would entirely remove the element from the DOM. No way to reverse that.

@Ruvee I did get an error indeed. Hence seeking help here. Well good to know it’s not PHP, I found it online 😀 What is it if I may ask? I don’t want to use CSS because it can be easily reversed. Just change display:none; to display:block; or something and voila — the element is visible. Isn’t using javascript similar? What if user disables scripts in web browser? Don’t know much about javascript.

2 Answers 2

As per our discussion in the comments, all you really need to do is .remove() the element. The following is the approach I’d take. First I’d check to make sure the element exists before attempting to remove it. If it’s there, then run jQuery’s .remove() .

This can’t be reversed via developer tools because it will comprehensively remove the element from the DOM. Now, if someone wants to open the developer tools and add something back into the DOM manually they can do that, but that’s kinda what developer tools are for right. To be able to identify this element, copy it and re-add it though, they’d have to be pretty quick.

I know you don’t want to add to a child theme or whatever so you’ll have to get this script into the flow somehow, not sure how you want to go about doing that.

Источник

Читайте также:  Php is less than or equal to
Оцените статью