简体   繁体   English

将HTML和CSS传递给Javascript

[英]Passing HTML and CSS to Javascript

I need to find a way to pass the visible div to javascript. 我需要找到一种方法将可见的div传递给javascript。 This may not even be the best way to accomplish what I'm trying to accomplish, so I'm open for other suggestions. 这甚至可能不是实现我想要完成的目标的最佳方式,所以我愿意接受其他建议。

All my site content opens in a single overlay. 我的所有网站内容都会在一个叠加层中打开。 When a button is clicked in the navigation, that content opens in the overlay. 在导航中单击按钮时,该内容将在叠加层中打开。 When another button is clicked, that content replaces the current content in the overlay. 单击另一个按钮时,该内容将替换叠加层中的当前内容。 And so on. 等等。

The best identifier (that I've spotted) of which overlay is open, is (CSS) display:block ... 打开覆盖层的最佳标识符(我发现)是(CSS) display:block ...
and all the hidden divs are display:none .... 并且所有隐藏的div都display:none ....

So I want to pass which div has the display:block to javascript (Note: all the div's have unique ID's) 所以我想传递哪个div有display:block to javascript(注意:所有div都有唯一的ID)

I'm sure this is something easy, But I can't seem to find it... 我确信这很容易,但我似乎无法找到它......

Thanks in advance for your time!! 在此先感谢您的时间!!

Each HTML element in JS has style property. JS中的每个HTML元素都具有样式属性。 You can read and change element style by calling for example 例如,您可以通过调用来读取和更改元素样式

document.getElementById('id').style.display

So you don't need to pass anything to JS, it's already there. 所以你不需要向JS传递任何东西,它已经存在了。

By reading your question it sounds like you need to identify which of your divs is the visible one. 通过阅读您的问题,听起来您需要确定哪些div是可见的div。 The easiest way to do that is add a class to all your divs with content, you can then use document.getElementsByClassName() to get a list of them and loop through to find which one is visible one based on a display property of block . 最简单的方法是使用内容为所有div添加一个类,然后可以使用document.getElementsByClassName()获取它们的列表,并根据blockdisplay属性循环查找哪一个是可见的。

<div class="content" style="display: none";>a</div>
<div class="content" style="display: block;">b</div>
<div class="content" style="display: none";>c</div>
<div class="content" style="display: none";>d</div>
<div class="content" style="display: none";>e</div>

var elements = document.getElementsByClassName("content");

for(i = 0; i < elements.length; i++) 
{
     if (elements[i].style.display == 'block')
     {
          // elements[i] = this is the visable div 
          alert('This elements[i] has a display of block; contents =  ' + elements[i].innerText);  
     }
}

The above script will output/alert 'b' as it is the visible div found. 上面的脚本将输出/警告'b',因为它是找到的可见div。 Fiddle link 小提琴链接

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

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