javascript 更改 div 标签内 img 的样式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8259013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
change the style of img inside a div tag
提问by N_F_S
Example:
例子:
<div class="test"><img src="test.jpg" style="display:none;" /></div>
How to change that with javascript, I know in css its:
如何使用 javascript 更改它,我在 css 中知道它的:
.test img {display:block;}
but in javascript I only know this:
但在javascript中我只知道这一点:
document.getElementById("test").style.display="block";
thats obviously the whole div tag , not the img.
那显然是整个 div 标签,而不是 img。
回答by RightSaidFred
If you're using an ID "test"
, you can do this.
如果您使用的是 ID "test"
,则可以执行此操作。
document.getElementById("test")
.getElementsByTagName("img")[0].style.display="block";
This uses getElementsByTagName
which returns a collection of the images found. The [0]
grabs the image at index 0
(the first image), and then applies the style.
这使用getElementsByTagName
返回找到的图像的集合。该[0]
抓住在索引图像0
(第一图像),然后应用的样式。
If you have a class "test"
, you can do this, but it won't work in IE7 and below:
如果你有一个 class "test"
,你可以这样做,但它不能在 IE7 及以下版本中工作:
var imgs = document.querySelectorAll(".test > img");
for( var i = 0; i < imgs.length; i++ ) {
imgs[i].style.display="block";
}
For the widest browser compatibility, you can do this:
为了获得最广泛的浏览器兼容性,您可以这样做:
function getElementsByClassName( root, clss ) {
var elems = document.getElementsByTagName('*'),
result;
clss = " " + clss + " ";
for( var i = 0; i < elems.length; i++ ) {
if( (" " + elems[ i ].className + " ").indexOf( clss ) > -1 ) {
result.push( elems[i] );
}
}
return result;
}
var tests = getElementsByClassName( document, "test" );
for( var i = 0; i < tests.length; i++ ) {
var img = tests[i].getElementsByTagName('img')[0];
if( img ) {
img.style.display="block";
}
}