最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I reverse an onclick event with another click? - Stack Overflow

programmeradmin3浏览0评论
function show()
{
var elem = document.getElementById("pop").querySelector('li:nth-child(3)');
elem.style.width = "500px";
}
</script>

I have this code attached to an onclick

<li onclick="show()">

The element is originally 200px and then turns into 500px when clicked. How do I make it work so that when I click it again it goes back to 200??

function show()
{
var elem = document.getElementById("pop").querySelector('li:nth-child(3)');
elem.style.width = "500px";
}
</script>

I have this code attached to an onclick

<li onclick="show()">

The element is originally 200px and then turns into 500px when clicked. How do I make it work so that when I click it again it goes back to 200??

Share Improve this question edited Feb 21, 2014 at 6:43 Pranav C Balan 115k25 gold badges171 silver badges195 bronze badges asked Feb 21, 2014 at 6:35 AllTheTime1111AllTheTime1111 1113 silver badges10 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

The best thing to do would be to use a CSS class to set the width. This has the advantage that:

  • You don't have to specify the width in multiple places (CSS and JS) (-> easier to maintain)
  • You don't have to know the default width of the element (-> more flexible)

Example:

CSS:

.wide {
    width: 500px;
}

HTML:

<li onclick="show(this)">...</li>

JS:

function show(elem) {
    elem.classList.toggle('wide');
}

DEMO

Have a look at the MDN documentation regarding classList for information about browser support. You can also find alternatives in this excellent question/answer about handling CSS classes on elements: Change an element's class with JavaScript

To learn more about event handling (ways to bind event handlers, information available inside event handlers, etc), have a look at the excellent articles at quirksmode.

function show() {
    var elem = document.getElementById("pop").querySelector('li:nth-child(3)'),
        width = parseInt(elem.style.width, 10);
    if (width === 500) {
        elem.style.width = "200px";
    }
    else {
        elem.style.width = "500px";
    }
}

Although, I'd probably name the function toggle or something similar and not inline the click handler.

Use a control variable

var clickControl = false;
function show()
{
    if(clickControl)
    {
        var elem = document.getElementById("pop").querySelector('li:nth-child(3)');
        elem.style.width = "500px";
        clickControl = !clickControl;
    }
    else
    {
        var elem = document.getElementById("pop").querySelector('li:nth-child(3)');
        elem.style.width = "200px";
        clickControl = !clickControl;
    }
}
发布评论

评论列表(0)

  1. 暂无评论