3

然而,测试一个简单的切换显示,第一次切换显示需要两次单击。之后它合而为一。

<html>
<head>
<style>
#carousel{border:2px solid blue;
width:1280px;
height:720px;}

#p2{visibility:hidden;}

#p1{display:block;}

#btn{position:absolute;
    top:2000px;}
</style>

<script src="mainScript.js"></script>
</head>

<body>

<div id="carousel">
    <img id="p1" src="pic1.jpg">
    <img id="p2" src="pic2.jpg">
</div>

<button type="button" id="button" onclick="clickEvent()">Click</button>

</body>
</html>

这是我的javascript:

function clickEvent(){
var p = document.getElementById("p1");
if(p.style.display == "block")
    p.style.display = "none";
else
    p.style.display = "block";
}

应该注意的是,我没有使用 jQuery,因为我发现的所有其他问题都与 jQuery 相关。

4

5 回答 5

5
function clickEvent(){
var p = document.getElementById("p1");
if(p.style.display == "none")
    p.style.display = "block";
else
    p.style.display = "none";
}

您还可以稍微简化一下:

p.style.display = p.style.display == "none" ? "block" : "none";
于 2012-12-31T16:22:58.657 回答
1

I have an update to my previous fiddle posted in my comment above. My previous fiddle still ran into the same problem after further testing of the double click.

After stepping through, the initial display value is coming back as "" not block. I'm not sure why its not taking your value you set in the <head></head> section but if you inline it like so:

<img id="p1" src="pic1.jpg" style="display: none;" />

it works correctly the first time with only one click of the button.

Here is my new updated fiddle demonstrating this.

I'm going to look more into why your styling in the <head></head> section but for now, here is a quick (and semi crude) fix.

Hope this helps and best of luck!

于 2012-12-31T16:40:40.570 回答
1

默认显示属性是“内联”,因此您的逻辑没有考虑到这一点。它在第一次运行时将其更改为块,因此它仍然可见,然后在第二次单击时将其隐藏(将显示设置为无)

于 2012-12-31T16:22:27.983 回答
0

您的答案

    function clickEvent(){
    var p = document.getElementById("p1");
    if(p.style.display === "block")
        p.style.display = "none";
    else
        p.style.display = "block";
    }

我改变了条件我有同样的问题,我意识到这是关于订单代码执行我的 CSS 样式的元素已经是“块”,我正在检查元素显示是否为“无”然后做显示块的事情,所以当我第一次点击时,它将显示更改为“无”,然后在第二次将显示更改为阻止,我希望我的解释很清楚

于 2021-11-21T10:55:11.433 回答
-2

同样的问题只需更换即可解决, "block" : "none";?"none" : "block"; 一次不需要双击切换按钮,单击即可。

于 2016-11-28T10:22:49.207 回答