使用 JavaScript 向 img 标签添加类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6304233/
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
Adding a class to img tags using JavaScript
提问by HackToHell
I am a learning javascript guy and I am trying to add the Image Hover Shadow Effect With CSS to my images and for that to work , I have to add an class to all my img tags , which is not possible manually so i am trying to write a javascript that does that and uses jquery , to do so .
我是一个学习 javascript 的人,我正在尝试将带有 CSS 的图像悬停阴影效果添加到我的图像中,为此,我必须向我的所有 img 标签添加一个类,这是手动不可能的,所以我正在尝试编写一个 javascript 来执行此操作并使用 jquery 来执行此操作。
it needs to add an class to img tag , such as this
它需要向 img 标签添加一个类,例如这个
From this
由此
<img border="0" height="75" src="http://3.bp.blogspot.com/-qhxaAUAJUVQ/TeocW4AuIiI/AAAAAAAABCo/IYy7hQ6-5VQ/s200/CSSEditLogo1.jpg" width="75"/>
to
到
<img border="0" class="imagedropshadow" height="75" src="http://3.bp.blogspot.com/-qhxaAUAJUVQ/TeocW4AuIiI/AAAAAAAABCo/IYy7hQ6-5VQ/s200/CSSEditLogo1.jpg" width="75"/>
Can anyone help :)
谁能帮忙:)
Thanks
谢谢
采纳答案by Emil
Are you sure you need the class. If you are planning to add a css class to all images and hook the shadow to it, you should be able to do it on the img tags directly.
你确定你需要这门课吗?如果您打算为所有图像添加一个 css 类并将阴影与其挂钩,您应该可以直接在 img 标签上执行此操作。
img:hover{
/*properties*/
}
回答by Facebook Staff are Complicit
To add the class to all of the images on your page with jQuery:
使用 jQuery 将类添加到页面上的所有图像:
$("img").addClass("imagedropshadow")
Without jQuery is is not very difficult either:
没有 jQuery 也不是很难:
var images = document.getElementsByTagName("img");
var i;
for(i = 0; i < images.length; i++) {
images[i].className += " imagedropshadow";
}
回答by Vivek
give an ID to your image, let's say it's imgId
and then write this jquery (if you want to add class to any specific img tag.)
给你的图像一个 ID,假设它是imgId
,然后编写这个 jquery(如果你想将类添加到任何特定的 img 标签。)
$(document).ready(function(){
$('#imgId').addClass('imagedropshadow');
});
for all img tag simply use this;
对于所有 img 标签,只需使用它;
$("img").addClass("imagedropshadow");
回答by James Allardice
回答by Xiezi
You can try this:
你可以试试这个:
$('img').addClass('imagedropshadow');
But I suggest you that you add an id or general class into the img tag for selecting.
但是我建议你在img标签中添加一个id或general class进行选择。