简体   繁体   English

Javascript:使用切换按钮隐藏和显示div标签

[英]Javascript: Hiding and Showing div tag with a toggle button

I'll get right to it: 我会正确的:

What I need to do is hide a particular div with the press of a button, and it's supposed to be a toggle, so basically: Press once to hide, press again to show, press again to hide etc... 我需要做的是按下按钮隐藏一个特定的div,它应该是一个切换,所以基本上:按一次隐藏,再按一次显示,再按一次隐藏等...

I want the hide/show rules to be done in CSS and the interaction in pure javascript (no jquery please). 我希望隐藏/显示规则在CSS中完成,并且在纯javascript中进行交互(请不要jquery)。 Well this is what I need to do, but I'm not quite sure how to execute the javascript code. 这是我需要做的,但我不太确定如何执行javascript代码。

html: HTML:

<p class="button">Show/hide<p>

<div> I want to hide this by pressing the button above</div>

css: CSS:

#showhide {
     display: none;
}

.button {
    display: block;
    height: 30px;
    width: 100px;
    background: green;
    text-align: center;
    padding-top: 10px;
    padding-left: 0px;
    font: 15px arial bold;
    border: 1px solid black;
    text-decoration: none;
    list-style:none;
    margin: 10px 0px 10px 0px;
}

http://jsfiddle.net/fyUJc/14/ http://jsfiddle.net/fyUJc/14/

Also, if you think this question doesn't belong here or is stupid, please try to refrain from being rude, I'm just trying to learn here. 此外,如果你认为这个问题不属于这里或者是愚蠢的,请尽量避免粗鲁,我只是想在这里学习。

You can make use an onclick method. 您可以使用onclick方法。 Have your HTML as: 将您的HTML设为:

<p class="button" onclick="toggle_visibility('hideMe')">Show/hide</p>
<div id="hideMe">I want to hide this by pressing the button above</div>

And have the following JavaScript: 并拥有以下JavaScript:

function toggle_visibility(id) 
{
    var e = document.getElementById(id);
    if (e.style.display == 'block' || e.style.display=='')
    {
        e.style.display = 'none';
    }
    else 
    {
        e.style.display = 'block';
    }
}

DEMO DEMO

Here is an updated JSFiddle of your code that works with native browser methods and implement a simple toggle component - http://jsfiddle.net/fyUJc/31/ 这是一个更新的JSFiddle代码,它使用本机浏览器方法并实现一个简单的切换组件 - http://jsfiddle.net/fyUJc/31/

var button = document.querySelector('.button');
button.addEventListener('click', function(event) {
    var target = document.querySelector(button.getAttribute('data-target'));
    if (target.style.display == "none") {
        target.style.display = "block";
        button.innerHTML = button.getAttribute('data-shown-text');
    } else {
        target.style.display = "none";
        button.innerHTML = button.getAttribute('data-hidden-text');
    }
});

By creating a toggle button you are entering the field of GUI and this is something very complex. 通过创建切换按钮,您将进入GUI领域,这是非常复杂的。

Current browser technologies doesn't provide a rich set of tools to help you with everything you need to handle in GUIs. 当前的浏览器技术不提供丰富的工具来帮助您处理GUI中需要处理的所有内容。 jQuery is of no help either, as GUIs are more about handling components and state than manipulating the DOM. jQuery也没有任何帮助,因为GUI更多的是处理组件和状态而不是操纵DOM。

Even that the above code works in Chrome, you still need to take care of browser differences in both DOM and event and you will need a better abstraction for the components. 即使上述代码在Chrome中有效,您仍然需要处理DOM和事件中的浏览器差异,并且您需要对组件进行更好的抽象。 There are quite a lot of problems that are not addressed in my code and that will be very difficult to address correctly if you write them from scratch every time. 我的代码中有很多问题没有解决,如果你每次都从头开始编写它们,那么很难正确解决。 Things like: 像:

  • How you initialize newly added togglers on the page ? 如何在页面上初始化新添加的切换器?
  • How you sync the state of the div and the button ? 你如何同步div的状态和按钮?
  • How you extend and plug into the button behavior ? 如何扩展和插入按钮行为?

I will strongly advise that you look into UI related libraries or frameworks that provide solutions for the common problems. 我强烈建议您研究与UI相关的库或框架,以便为常见问题提供解决方案。 See ReactJS, Dojo or Sencha (ex. ExtJS) to name a few. 请参阅ReactJS,Dojo或Sencha(例如ExtJS),仅举几例。 Look for frameworks that define a Widget/Component life-cycle and ways to extend and define custom ones. 寻找定义Widget / Component生命周期的框架以及扩展和定义自定义生命周期的方法。

Browser technologies just don't provide the proper abstractions for making UI components. 浏览器技术不能为制作UI组件提供适当的抽象。

An alternative solution just using 'onclick' attribute inside your HTML tag: 在HTML标记中使用“onclick”属性的替代解决方案:

<!DOCTYPE html>
    <html>
        <head>
           <script>
               function toggle(){
                   var div = document.getElementById("divSection");
                   if (div.style.display =='block'){
                       div.style.display = 'none';
                       return;
                   }
                   div.style.display ='block';
             }
           </script>
        </head>

        <body>
            <p>Click the button to trigger a function.</p>
            <p class="button" onclick="toggle()">Show/hide</p>
            <div id='divSection'> I want to hide this by pressing the button above</div>
        </body>
    </html>

I hope it helps. 我希望它有所帮助。

You can add attach an event listener to the P tag and have that call a Toggle() function to swap the display value as shown below. 您可以向P标记添加附加事件侦听器,并调用Toggle()函数来交换显示值,如下所示。

Example here - JSFiddle 这里的例子 - JSFiddle

function Toggle() {
    var div = document.getElementsByTagName('div')[0];

    if (div.style.display == 'none') {
        div.style.display = 'block';
    } else {
        div.style.display = 'none';
    }
}

(function () {

    var button = document.querySelectorAll(".button");

    for (var i = 0; i < button.length; i++) {
        if (button[i].addEventListener) {
            button[i].addEventListener("click", function () {
                Toggle();
            });
        } else {
            button[i].attachEvent("click", function () {
                Toggle();
            });
        }
    }
})();

Though you would be better adding IDs to your elements to make them easier to reference. 虽然您最好将IDs添加到元素中,以便更容易引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM