js怎么实现三个按钮点击那个那个更换样式

JavaScript021

js怎么实现三个按钮点击那个那个更换样式,第1张

可以尝试以下操作:

html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/htmlcharset=gb2312" />

<title>js控制按钮样式切换</title>

<link href="css/my.css" rel="stylesheet">

</head>

<script type="text/javascript">

//左边按钮的点击事件

window.onload = function(){

var arr = document.getElementsByTagName('button')

for(var i = 0i<arr.lengthi++){

arr[i].onclick = function(){

//this是当前激活的按钮,在这里可以写对应的操作

if(this.className == 'btn1'){

this.className = 'btn2'

var name = this.id

var btn = document.getElementsByClassName('btn2')

for(var j=0j<btn.lengthj++){

if(btn[j].id!=name){

btn[j].className = 'btn1'

}

}

}

}

}

}

</script>

<body>

<div id="main" style="margin:auto 0">

<!--四个按钮-->

<div style="margin-top:2em">

<div style="width:20%"><button id = "1" type = "button">按钮1</button></div>

<div style="width:20%"><button id = "2" type = "button">按钮2</button></div>

<div style="width:20%"><button id = "3" type = "button">按钮3</button></div>

<div style="width:20%"><button id = "4" type ="button">按钮4</button></div>

</div>

</div>

</body>

</html>

JS控制css样式的几种方式

我们在js的工作学习中总会遇到一些不轻易通过style属性动态加载css样式的情况(eg:伪类的样式控制,动画的样式控制),这里总结一下js改变样式的几种方法:

1,通过style属性或者setAttribute()来更改样式

2,如果只是改变伪类(after,before)的content内容也可以这么做

3,通过更改类名来更改样式

4,那么重点来了:利用document.styleSheets我们获取到所有样式表,然后选择一个样式表通过 insertRule 来添加样式;也可以创建新的cssRules,通过addRule()来添加样式

5,动态加载样式表

如果需要更改的样式比较多,还是建议通过动态加载样式的方式来改变页面样式

本文来自PHP中文网,原文地址: https://www.php.cn/website-design-ask-479590.html  推荐视频教程:《 js基础教程 》

方法步骤:

先获取要改变css的元素。

改变这个元素的style属性。

eg:下面是改变div的背景色,改为蓝色。

<style>

div{width:200pxheight:200pxbackground:#f00}

</style>

<div>改变背景色</div>

<script>

var div = document.getElementsByTagName("div")

div.style.background = "blue"

</script>