繁体   English   中英

从隐藏/无开始切换显示/隐藏

[英]toggle show/hide starting from hide/none

我正在一个网站上工作,我想通过单击按钮/单词来显示和隐藏图像。 我使用了一些代码并且它正在工作:

function myFunction() {
  var x = document.getElementById("myDIV");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

与之前关于此主题的堆栈溢出问题中使用的问题类似:

var button = document.getElementById('button'); // Assumes element with id='button'

button.onclick = function() {
    var div = document.getElementById('newpost');
    if (div.style.display !== 'none') {
        div.style.display = 'none';
    }
    else {
        div.style.display = 'block';
    }
};

但是,我希望在您进入或刷新站点时隐藏图像而不是显示图像。 因此,与其首先显示图像并在您单击该词时将其隐藏,我希望它在您单击该词时隐藏并显示。 我如何更改脚本以实现这一点?

我试着切换“无”和“阻止”,但没有用哈哈...

谢谢

您可以在脚本运行时隐藏图像,也就是加载或刷新页面时。 所以只需添加一行就足够了。

const button = document.getElementById("button") // Assumes element with id='button'
const imageElement = document.getElementById("newpost")

// Hide the image at the start
imageElement.style.display = "none"

// Toggle it on click
button.addEventListener('click', () => {
    imageElement.style.display =
        imageElement.style.display === "none" ? "block" : "none"
})

我还修改了您的代码,使用ternary operator使其更易于阅读。

如果您使用的是示例中的.onClick方法:首选使用addEventListener而不是.onX方法。 有关MDN和此答案的更多信息。

暂无
暂无

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

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