js中设置样式的几种方式(setAttribute,className)

本文介绍如何使用JavaScript实现点击不同按钮,动态替换网页背景色的功能。通过代码实例,展示了如何利用事件监听和CSS样式来完成这一交互效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以设置背景色为例子


可以用单一的backgroundColor
可以用className
可以用setAttributesetAttribute removeAttribute)为一组

实例代码(实现效果点击一个按钮,就把整个背景色替换,点击其他的就换其他的)

<html>

<head>

<title></title>

<style type="text/css">
    .bg{
        background-color : "blue" ;
    }    
</style>

<script language="javascript" type="text/javascript">
    window.onload = function(){
    
        $("redC").onclick = function(){
            document.body.removeAttribute("className","bg");
            document.body.style.backgroundColor = "red";
        }
         $("blueC").onclick = function(){
            document.body.style.backgroundColor = "";
           
            document.body.setAttribute("className","bg");
//            document.body.className = "bg";
        }
        
        $("pinkC").onclick = function(){
          document.body.removeAttribute("className","bg");
            document.body.style.backgroundColor = "pink";
        }
        
        $("blackC").onclick = function(){
          document.body.removeAttribute("className","bg");
            document.body.style.backgroundColor = "black";
        }
    }
    
    function $(uid){
        return document.getElementById(uid);
    }
</script>

</head>

<body>
<input type="button" value="red" id="redC"/>
<input type="button" value="blue" id="blueC"/>
<input type="button" value="pink" id="pinkC"/>
<input type="button" value="black" id="blackC"/>
</body>

</html>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值