简体   繁体   English

遍历div并显示不同内容的Javascript

[英]Javascript to cycle through divs and show different content

I'm trying to create some javascript for my web page that is able to change divs and the content that's inside on a mouse click. 我正在尝试为我的网页创建一些JavaScript,该Javascript能够更改div和单击鼠标中的内容。 I'm using display: none; 我正在使用display: none; and display: block; display: block; to determine which div is shown. 确定显示哪个div。

function CycleDivsWithClick(div1, div2, div3, div4) {
  d1 = document.getElementById(div1);
  d2 = document.getElementById(div2);
  d3 = document.getElementById(div3);
  d4 = document.getElementById(div4);

  if (d1.style.display == "block") {
    d1.style.display = "none";
    d2.style.display = "block";
    d3.style.display = "none";
    d4.style.display = "none";
  } else if (d2.style.display == "block") {
    d1.style.display = "none";
    d2.style.display = "none";
    d3.style.display = "block";
    d4.style.display = "none";
  } else if (d3.style.display == "block") {
    d1.style.display = "none";
    d2.style.display = "none";
    d3.style.display = "none";
    d4.style.display = "block";
  } else if (d4.style.display == "block") {
    d1.style.display = "block";
    d2.style.display = "none";
    d3.style.display = "none";
    d4.style.display = "none";
  } else {
    d1.style.display = "block";
  }
}

I can only get this code to work if I add the final else statement shown above. 如果添加上面显示的最终else语句,则只能使此代码正常工作。 Even then the script has to be clicked once before it will work as expected. 即使这样,脚本也必须单击一次,然后才能按预期工作。 Why does it do this? 为什么这样做呢? Even though my div1 (alpha) is initially set to display: block; 即使我的div1(alpha)最初设置为display: block; from the css. 从CSS。

Example code in CodePen here 这里的CodePen中的示例代码

My full code actually displays background images. 我的完整代码实际上显示背景图像。 My hope is to get it to pre-download all images so it won't load the image upon the mouse click. 我的希望是让它预先下载所有图像,这样在单击鼠标时就不会加载该图像。

I'd also prefer to avoid jQuery for now as I'd like to learn the basics before progressing. 我还希望暂时避免使用jQuery,因为我想在学习之前先学习基础知识。

The problem is that the element.style returns the properties set through the style attribute ( which is not set initially but is instead done through the CSS rules ). 问题是element.style返回通过style属性设置的属性( 最初没有设置,而是通过CSS规则完成 )。

You could use the window.getComputedStyle method 您可以使用window.getComputedStyle方法

Demo at http://codepen.io/gpetrioli/pen/WrQMvw?editors=001 演示位于http://codepen.io/gpetrioli/pen/WrQMvw?editors=001

for your extra else statement in jquery code you can change your html code belong alpha div like this 对于jquery代码中的其他else语句,您可以像这样更改html代码属于alpha div

<div id="bravo" style="display:block;">
    Some text within Bravo
  </div>

Sample 样品

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

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