如何设置图像的alt属性的样式 [英] How to style an image's alt attribute

查看:1111
本文介绍了如何设置图像的alt属性的样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图显示img标记的(外部)html,但是我希望alt属性显示为红色.

I am trying to display the (outer)html of an img tag, but I want the alt attribute to be in red.

我获取字符串的方式:

var img_outerHTML = img[0].outerHTML;

这给了我字符串:

<img alt="main-logo" src="main-logo.png">

那我怎么让main-logo变成红色?
谢谢!

So how can I have main-logo to be red?
Thank you!

编辑

感谢techfoobar提供解决方案以及所有其他提供帮助的人!
这是一个 jsFiddle示例.

Thanks to techfoobar for the solution and everyone else that helped!
Here is a jsFiddle Example.

推荐答案

假设您正在尝试在另一个元素中显示外部HTML ,您可以执行以下操作:

Assuming you are trying to display the outer HTML as such in another element, you can do:

var s = '<img alt="main-logo" src="main-logo.png">';
// As pointed out by user bfavaretto, we need to html-encode it before
// injecting the <span>
s = $('<div/>').text(s).html();
s = s.replace(/alt=\"([a-zA-Z0-9\s-]*)\"/, 'alt="<span class=\'red\'>$1</span>"');

完成后,这会将HTML字符串转换为(注意:跨度之外的所有其他内容都将进行HTML编码.鸣谢: https ://stackoverflow.com/a/1219983/921204 )

Once done, this will transform the HTML string to (Note: that everything other that the span will be HTML encoded. Credit: https://stackoverflow.com/a/1219983/921204)

<img alt="<span class='red'>main-logo</span>" src="main-logo.png">

实际上,它将是:

&lt;img alt="<span class='red'>main-logo</span>" src="main-logo.png"&gt;

然后在您的CSS中添加:

And in your CSS, add:

span.red {
    color: red;
}

这篇关于如何设置图像的alt属性的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆