带有onclick和2个条件的扰流板代码

Spoiler code with onclick and 2 conditions

本文关键字:代码 条件 onclick 2个 带有      更新时间:2024-04-05

我的主页上有一个剧透代码。代码如下:

<div id="spoiler" style="display:none"> 
HIDDEN CONTENT HERE
</div> 
<a display="initial" 
   id="button" 
   title="Click to show/hide content" 
   type="button" 
   onclick="if(document.getElementById('spoiler')                     
                       .style.display=='none') {
               document.getElementById('spoiler')                                    
                       .style.display=''
            }else{
               document.getElementById('spoiler')               
                       .style.display='none'
            }">
   Show hidden content
</a>

我现在想做的很简单:点击元素"按钮"后,将显示隐藏的内容,并且锚点<a>将变为不可见。

所以我想要的是:onclick:如果元素"spoiler"显示=none AND元素"button"显示=initial,则元素"sporter"将变为display=initial AND元素"按钮"应变为display=none

这可能吗?

jquery中的这段代码将解决您的问题。我希望这是你想要的。

$('#button').click(function() {
        $('#spoiler').css('display', 'block');
      $(this).hide();
    });

我在这里也有演示。

JavaScript唯一的解决方案如下:

<div id="spoiler" style="display:none"> 
HIDDEN CONTENT HERE
</div> 
<a display="initial" id="button" title="Click to show/hide content" type="button" onclick="document.getElementById('spoiler').style.display='block';
  document.getElementById('button').style.display='none'">Show hidden content</a>

尝试以下代码。JSFiddle。

<div id="spoiler" style="display:none" onclick="this.style.display='none';">
   HIDDEN CONTENT HERE
</div>
<a display="initial" id="button" title="Click to show/hide content" type="button" onclick="document.getElementById('spoiler').style.display='block';">Show hidden content</a>

display="initial"不是有效的属性。此外,将所有这些代码放在onclick属性中可以防止在其他扰流器块中重用该代码。最好的解决方案是使用script标签来分离关注点和可重用性。

以下是您所需的基本信息:

<div id="spoiler" style="display:none">HIDDEN CONTENT HERE</div> 
<a onclick="showSpoiler(this,'spoiler')">Show hidden content</a>
<script>
function showSpoiler(buttonNode, spoilerId) {
    document.getElementById(spoilerId).style.display='block';
    buttonNode.style.display='none';
}
</script>