javascript更改元素背景 [英] javascript change element background

查看:98
本文介绍了javascript更改元素背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是HTML

<p>texjksdgfjl sdjfg sjdfg</p>
<p>&nbsp;</p>
<p>texjksdgfjl sdjfg sjdfg</p>
<p>&nbsp;</p>
<p>texjksdgfjl sdjfg sjdfg</p>

这是JavaScript

This is the JavaScript

var d = document.getElementsByTagName("p"); 

for (var i=0;i<d.length;i++)
{ 
    var text = d[i].textContent;

    if (text.length===1){
        d[i].style.background ='blue';
    }
    else {
        d[i].setAttribute("backgroundColor", "red");
    }
}

(显然)我可以做我想做的事 - 包含一些文本的p元素的不同背景,而不是生成为<的p元素。 p>& NBSP; < / p>

(Obviously) I can do what I want to do - different background for p elements that contain some text as opposed to p elements which are generated as < p > & nbsp; < /p >

但为什么setAttribute不起作用?
我必须错过一些非常简单的东西,但对于我的生活,我无法想象它是什么。
纯JS请,没有jQuery,没有MooTools,没有其他库。

But why doesn't the setAttribute work? I must be missing something very simple, but for the life of me I cannot imagine what it is. Pure JS please, no jQuery, no MooTools, no other library.

这是测试小提琴:在此输入链接说明

推荐答案

嗯, setAttribute 函数没有按你的想象做。

Well, the setAttribute function doesn't do what you think it does.

如果你检查jsfiddle中的元素,你会看到这个:

If you inspect the elements in your jsfiddle, you see this:

... <p backgroundcolor="red" ...>

肯定不是你想要的。你想要的是这样的:

and this is definitely not what you want. What you want is something like this:

setAttribute("style", "background-color: red;");

所以它会变成

... <p style="background-color: red;" ...>

这篇关于javascript更改元素背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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