如何在jquery中设置图像元素的背景颜色 [英] how to set background color of image element in jquery

查看:97
本文介绍了如何在jquery中设置图像元素的背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我动态创建了图像元素。我想设置图像元素的背景颜色。它不适用于以下代码。

I have created image element dynamically. I want to set background color of the image element. it is not working for the following code.

var img = $('<img />', {
                id: 'img1',
                src: '/ProductImages/' + products[1].PictureFileName
            }).appendTo(span);
            img.width(150); img.height(200);
            img.css('background-color', '#efeeef');
            img.className = 'bkcolor';

推荐答案

('< img />',{
id:'img1',
src:'/ ProductImages /'+ products [1] .PictureFileName
})。appendTo(span);
img.width(150); img.height(200);
img.css('background-color','#efeeef');
img.className ='bkcolor';
('<img />', { id: 'img1', src: '/ProductImages/' + products[1].PictureFileName }).appendTo(span); img.width(150); img.height(200); img.css('background-color', '#efeeef'); img.className = 'bkcolor';


请参阅我对该问题的评论。我不会在这里使用jQuery方式。本机HTML元素对象以更好,更易于维护的方式执行,Visual Studio Intellisense也支持这种方式。而不是两个最后一行,我会写

Please see my comment to the question. I would not use jQuery way here. The native HTML element object does in better, more maintainable manner which is also supported by Visual Studio Intellisense. Instead of two last line, I would write
img.style.backgroundColor = //... some color



请参阅: HTMLElement.style - Web API | MDN [ ^ ]。



请注意,此样式将应用于已应用于元素的样式之上。另请注意,此颜色与图像内容无关;如果图像完全填满 img 元素,你将看不到任何色差,因此,要看到它,你需要有半透明图像,或者里面有一些填充 IMG 。它可能是另一种(太微不足道)的原因,你可能看不出差异。



-SA


Please see: HTMLElement.style - Web APIs | MDN[^].

Note that this style will be applied on top of the style already applied to the element. Also note that this color has nothing to do with the content of the image; you won't see any color difference if the image fully fills the img element, so, to see it, you either need to have semi-transparent image, or some padding inside img. It could be another (way too trivial) reason why you may not see the difference.

—SA

这篇关于如何在jquery中设置图像元素的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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