Css on click display none

Добавляем и удаляем display:none по клику

нужно сделать так что бы по умолчание все контейдеры кроме первого были скрыты через display:none
далее при клике по ссылки который не спрятан получал свой display:none
а вместо него появлялся другой блок который был скрыт.
я не знаю как это все связать вместе

Добавлено через 37 минут
вот так я сделал что бы раскрывались скрытые блоки

div id="sample-1" style='display:none;'>/div> ul> li onclick="view('sample-1')">a href="/#" id="cat_1">1/a>/li> /ul>
function view(idDiv) { var v = document.getElementById(idDiv); if(v.style.display != 'block') v.style.display = 'block'; }

но как при этом убрать уже раскрытый блок когда открывается следующий? они просто будут открываться один под другим

Удаляем/добавляем папки в окне «Этот компьютер» в Windows 8.1
недавно начал изучать сей язык программирования зацените скрипт в архиве: (может будут какие-то.

Display: block; по клику на другом div
Первый опыт js, пока очень плохо разбираюсь. Не могу понять в чём допустил ошибку. Попробовал.

come Display This video mode change computer display input to 1240 x . 60hz
Здравствуйте, у моего знакомого полетел компьютер,пожалуйста помогите его вернуть к жизни,очень.

Читайте также:  Java util date data

Cannot display this video mode,change computer display input to 1024×768 60 HZ
Компьютер стабильно работал,и внезапно появился черный экран на котором написано "Cannot display.

div id="sample-1">z/div> div id="sample-2" style='display:none;'>zz/div> div id="sample-3" style='display:none;'>zzz/div> ul> li onclick="view('sample-1')">a href="#" id="cat_1">1/a>/li> li onclick="view('sample-2')">a href="#" id="cat_1">1/a>/li> li onclick="view('sample-3')">a href="#" id="cat_1">1/a>/li> /ul>
function view(idDiv){ var divs = document.getElementsByTagName('div'); for(var i = 0; i  divs.length; i++){ if(divs[i].id == idDiv){ divs[i].style.display = 'block'; continue; } divs[i].style.display = 'none'; } }

только эта функция будет проверять и скрывать ВСЕ блоки

на странице. если у вас на странице много блоков, а не только эти три, надо как то по другому обращаться к ним. например надо дать какое нибудь имя класса для этих трех блоков и обращаться по классу к ним, то есть:
div id="sample-1" сlass='какой-то-класс'>z/div> div id="sample-2" сlass='какой-то-класс' style='display:none;'>zz/div> div id="sample-3" сlass='какой-то-класс' style='display:none;'>zzz/div>
var divs = document.getElementsByClassName('какой-то-класс');

не совсем то.такой вариант просто показывает/скрывает блок при клики на одну и ту же ссылку. а задача состоит в том что бы когда открывался новый div то автоматически скрывался бы тот который был до него

RapCore, либо я вас недопонимаю, либо вы говорите не то, что хотите)))
выше приведенный код так и работает. при клике на первую ссылку показывается блок номер 1. и сколько бы вы раз не кликали на ссылку, все равно будет показываться первый блок. соответственно то же самое с остальными ссылками. при клике на другую ссылку скрываются все блоки и открывается блок, соответствующий ссылке. вот пример

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
 html> head> /head> body> div id="sample-1">Клик по ссылке 1/div> div id="sample-2" style='display:none;'>Клик по ссылке 2/div> div id="sample-3" style='display:none;'>Клик по ссылке 3/div> ul> li onclick="view('sample-1')">a href="#" id="cat_1">1/a>/li> li onclick="view('sample-2')">a href="#" id="cat_1">1/a>/li> li onclick="view('sample-3')">a href="#" id="cat_1">1/a>/li> /ul> script> function view(idDiv)< var divs = document.getElementsByTagName('div'); for(var i = 0; i < divs.length; i++){ if(divs[i].id == idDiv){ divs[i].style.display = 'block'; continue; } divs[i].style.display = 'none'; } } /script> /body> /html>

Источник

A CSS-Only Click Handler Using the :target Pseudo-Class (No JavaScript)

A CSS-Only Click Handler Using the :target Pseudo-Class (No JavaScript)

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

There’s often a point when you’re building a website, especially a simple landing page, when you realize you’re going to have to introduce some JavaScript. CSS, however, can often do a lot more than we give it credit for. Here we’ll look at creating click handlers with only CSS! 🔥 Let’s say we’re building an HTML and CSS landing page and we decide we want a “See more!” button to display a section of text. As soon as we think of a click event, usually it leads us to one word: JavaScript. As web developers, most of us spend a lot of time with JavaScript— and that’s great! However, there are tons of things we can do with just CSS that we may not even know about! 💅

The CSS Pseudo-Class :target

There are lots pseudo-classes in CSS that can help us style elements in different states. For example, you can style a button when it’s hovered, active, focused, etc. One pseudo-class you might not have heard about, though, is the :target pseudo-class. The :target pseudo-class is used to select an element when that element’s ID matches part of the current URL.

When Would an Element’s ID Match a URL?

Using an Anchor Tag to Jump Positions on the Page

a href='https://alligator.io'> Click me! 🐊 a> 

However, if you want your user to stay on the current page and jump down to the footer, for example, all you have to do is set an ID on the footer and use that ID for the href value in the tag.

a href='#footer'> Go to the footer! a> 

When the user clicks on this footer link, the page will jump to the footer and their current URL will get updated to look like:

https://www.imawebsite.com/#footer 

Creating Click Handlers with :target

Now that we know how to create a target with HTML, how do we use that target to create a click handler without any JavaScript? Thankfully, it takes just a little CSS! 🌈 Using our “See more!” button example from above, let’s start by creating a link to see more text:

a href='#seeMore'> See more! a> section id='seeMore'> p> Here's some more info that you couldn't see before. I can only be seen after you click the "See more!" button. p> section> 
https://www.imawebsite.com/#seeMore 

The problem we have now is that the #seeMore section is visible to the user even though it’s not supposed to be yet! 🙈 Since this is all the HTML we’ll need so far, let’s add our CSS to manage showing the text block on click. First, let’s hide the text that shouldn’t show yet.

style> #seeMore  display: none; > style> 

Now the text in the #seeMore section doesn’t show on load or when you click the “See more!” button. This is where the :target styling comes in. Let’s use the :target pseudo-class to update the styling when the “See more!” button gets clicked.

It is literally as simple as that! On load, our text section will not show. As soon as you click the “See more!” button, it will add #seeMore to the URL and the #seeMore section becomes the target. Once #seeMore becomes the target, it will have its :target styling applied, which displays the text. 🥳

Using :target to Toggle the Display

If an element wasn’t visible to begin with, you will probably want the option to hide it again. Luckily, we can do that with just one more line of HTML (no CSS!) 💪 Using the same example as above, let’s expand the HTML to include a “Hide text” button.

a href='#seeMore'>See more!a> section id='seeMore'> p> Here's some more info that you couldn't see before. I can only be seen after you click the "See more!" button. p> a href='#'>Hide texta> section> 

With the URL updated, #seeMore is no longer the target, and the #seeMore:target styling no longer gets applied. The block of text (including the “Hide text” button) will, therefore, go back to having the display: none; styling applied. In short, update the URL and the text that was originally not displayed goes back to not being displayed. We officially have a way to toggle the text! ✨

Examples of When to Use :target

  • Click a hamburger icon to show your site’s navigation menu. Include an icon to close the navigation.
  • Click an icon to display a modal. (Note: Make sure your modals are accessible if you’re going to use them! 🤓)
  • Update the styling of the currently selected tab in your navigation bar when it gets clicked.

Browser Support

The browser support for the :target pseudo-class is fantastic and you basically don’t need to worry about it unless you’re supporting IE8. As always, though, check Can I Use to be sure. 🚀

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Как показать div блок при нажатии на ссылки?

Как сделать так, чтобы он закрывался, когда ты нажимаешь в любую область сайта?

doniys_a

Примерно вот так:
document.body.onclick = function () document.getElementById(‘box’).style.display = ‘none’;
>
Суть в установке события на глобальную область: либо враппер страницы, либо body.

BadassRolf

kosolapus

document.onclick=function() < document.getElementById('box').style.display='none'; >//Если все же надо давать возможность кликать по самому элементу, то так: document.onclick=function(e)

BadassRolf

function openbox(id) <
display = document.getElementById(id).style.display;

if(display==’none’) document.getElementById(id).style.display=’block’;
>else document.onclick=function() document.getElementById(‘box’).style.display=’none’;
>
>
>

kosolapus

BadassRolf: Так и не должно, все верно. Вы по выполнению функции вешаете обработчик, а зачем — не совсем понятно

Источник

Оцените статью