1

例如:我想获取当前为黄色的 body 的背景颜色并将其更改为蓝色:

   document.body.style.backgroundColor =  document.body.style.backgroundColor.replace("yellow", "blue");

没用,为什么??那么如何使用javascript更改正文的背景颜色?主要问题是为什么我不能使用.replace方法document.body.style.backgroundColor

4

2 回答 2

1

以下就足够了:

document.body.style.backgroundColor = 'blue';

在您的代码中,如果backgroundColor yellow它将替换为blue. toLowerCase()如果这是您需要的,我认为在更换之前使用方法会更好。

document.body.style.backgroundColor = 
document.body.style.backgroundColor.toLowerCase().replace("yellow", "blue");

您还可以使用正则表达式(如@nnnnnn 所建议)进行区分大小写的替换;

document.body.style.backgroundColor = 
document.body.style.backgroundColor.replace(/yellow/i, "blue");
于 2013-10-13T09:03:35.087 回答
0

当然,你可以,检查这个小提琴http://jsfiddle.net/thefourtheye/PexeK/

<body style="background-color:yellow">
    <input type="button" onclick="changeColor()" value="Change Color" />
</body>
<script>
    function changeColor() {
        document.body.style.backgroundColor = document.body.style.backgroundColor.replace("yellow", "blue");
    }
</script>
于 2013-10-13T09:17:41.040 回答