简体   繁体   English

使用 JavaScript 将 class 添加到 img 标签

[英]Adding a class to img tags using JavaScript

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. 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编写一个 javascript 来执行此操作并使用 jquery 来执行此操作。

it needs to add an class to img tag, such as this它需要添加一个 class 到 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谢谢

To add the class to all of the images on your page with jQuery:使用 jQuery 将 class 添加到页面上的所有图像:

$("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";
}

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(如果您想将 class 添加到任何特定的 img 标签。)

$(document).ready(function(){ 
      $('#imgId').addClass('imagedropshadow');
});

for all img tag simply use this;对于所有 img 标签,只需使用它;

$("img").addClass("imagedropshadow"); 

Are you sure you need the class.您确定需要 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 class 添加到所有图像并将阴影钩到它,您应该可以直接在 img 标签上执行此操作。

img:hover{
 /*properties*/
}

You can use the addClass function with jQuery.您可以将addClass function 与 jQuery 一起使用。 See the API here for examples.有关示例,请参见此处的 API。

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或者通用的class进行选择。

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

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