javascript 根据类名显示/隐藏 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11229474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:27:48  来源:igfitidea点击:

show/hide div based on class name

javascript

提问by Alaa Gamal

i have a show/hide div javascript function

我有一个显示/隐藏 div javascript 功能

i want convert it to work with class name instead of style

我想将它转换为使用类名而不是样式

This is my function that i want convert it

这是我要转换的函数

<script>
function toggle(e, id) {
    var el = document.getElementById(id);
    el.style.display = (el.style.display == 'none' || el.style.display == '') ? 'block' : 'none';
    toggle.el = el;
    if (e.stopPropagation) e.stopPropagation();
    e.cancelBubble = true;
    return false;
}
document.onclick = function() {
    if (toggle.el) {
        toggle.el.style.display = 'none';
    }
}
</script>

i want convert it to work with class name,

我想将它转换为使用类名,

for example:

例如:

#hidden{
display:none;
}
#shown{
display:block;
}
function toggle(e,id){
if(el.class=='hidden'){
el.setAttribute("class", "showen");
}
//etc...
}

回答by hsanders

First and foremost your CSS is invalid, classes are defined in CSS using . and not #. #'s define IDs, which are always unique to one element in the document. A class on the other hand, is as the name implies, a type of thing that many objects can be. An ID is like the name of a dog "Fido", you should have only one dog named "Fido", whereas a class is like a dog breed, you could have many cockapoos, but each must have a unique name. The other answers to this question fail to correct your CSS, and if you don't correct that, it won't work.

首先,您的 CSS 无效,类是使用 .css 在 CSS 中定义的。并不是 #。# 定义了 ID,它对于文档中的一个元素总是唯一的。另一方面,顾名思义,类是许多对象都可以成为的一种事物。一个ID就像一只狗的名字“Fido”,你应该只有一个叫“Fido”的狗,而一个类就像一个狗品种,你可以有很多cockapoos,但每个人都必须有一个唯一的名字。这个问题的其他答案无法更正您的 CSS,如果您不更正,它将无法正常工作。

 .hidden{
   display:none;
 }
 .shown{
   display:block;
 }

Secondly, it would make your life a lot easier if you used a JavaScript framework, such as JQuery. Here is the same thing written using JQuery (Jquery library include omitted)

其次,如果你使用 JavaScript 框架,比如 JQuery,它会让你的生活更轻松。这是使用 JQuery 编写的相同内容(省略了 Jquery 库)

$(document).click(function() {
    var toggleElements = $(".toggleMe");
    $.each(toggleElements, function (key, value) {
       if (value.hasClass('hidden')) {
           value.removeClass('hidden');
           value.addClass('shown');
       } else {
           if (value.hasClass('shown')) {
               value.removeClass('shown');
               value.addClass('hidden');
           }
       }
    });
});

The other thing I'd recommend to improve this would be to instead of using display: block to show, because display:block doesn't necessarily imply simply "shown" vs. "hidden", it implies information about how that element is handled in terms of display, meaning a block element is treated as its full height/width with whitespace as needed no matter, what and any HTML elements next to it are forced to the next line unless explicitly designed otherwise. What you should do instead is simply remove the hidden class.

我建议改进的另一件事是不要使用 display:block 来显示,因为 display:block 不一定意味着简单地“显示”与“隐藏”,它暗示了有关如何处理该元素的信息就显示而言,这意味着块元素被视为其全高/宽度,并根据需要使用空格,除非明确设计,否则它旁边的任何 HTML 元素和任何 HTML 元素都将被强制到下一行。你应该做的只是删除隐藏的类。

回答by sylverfyre

A little off-topic, but this is even easier if you're using the jquery library.

有点离题,但如果您使用 jquery 库,这会更容易。

$(".yourclass").hide();
$(".yourclass").show();

To test if something is showing with jquery:

要测试是否使用 jquery 显示某些内容:

if ($(".yourclass").is(":visible"))

Obviously there's reasons you might not want to be using jquery, but it has some nifty tools to make things like this easier.

显然,您可能不希望使用 jquery 是有原因的,但它有一些漂亮的工具可以让这样的事情变得更容易。

回答by Jason McCreary

Checking for the existing of a class name in classNameis not as straightforward as one might think. The following article has an excellent explanation of this and includes the custom function: hasClassName()

检查类名className是否存在并不像人们想象的那么简单。以下文章对此进行了很好的解释,并包括自定义功能:hasClassName()

function hasClass(el, class_to_match) {
    if (el && el.className && typeof class_to_match === "string") {
        var c = el.getAttribute("class");
        c = " " + c + " ";
        return c.indexOf(" " + class_to_match + " ") > -1;
    }
    else {
        return false;
    }
}

Then you can simply update your togglefunction:

然后你可以简单地更新你的toggle函数:

function toggle(el, id) {
  if (hasClassName(el, 'hidden')) {
    el.setAttribute("class", "showen");
  }
}

Note:I do advocate using such a Javascript framework/library if you are doing such things often. But if toggling an element's display is only things you do, then I believe they're overkill.

注意:如果你经常做这样的事情,我确实提倡使用这样的 Javascript 框架/库。但是如果切换元素的显示只是你做的事情,那么我相信他们是矫枉过正的。