使用原生JS 修改 DIV 属性
2019-08-14 10:04:00来源:博客园 阅读 ()
本例参考并改进自:https://www.jianshu.com/p/2961d9c317a3
大家可以一起学习!!
<!DOCTYPE html>
<html lang="CH-ZN">
<head>
<meta charset="utf-8">
<title>按键修改DIV属性</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
body {
text-align: center;
}
button {
margin-top: 20px;
width: 100px;
height: 60px;
background-color: green;
color: #fff;
border: none;
}
div {
width: 400px;
height: 400px;
background-color: black;
margin: 20px auto;
display: block;
transition: all 1s;
}
</style>
</head>
<body>
<button>变宽</button>
<button>变高</button>
<button>变色</button>
<button>变圆</button>
<button>隐藏</button>
<button>重置</button>
<div></div>
<script type="text/javascript">
/**
* 修改属性
* @param1 元素
* @param2 属性(注意这里是字符串类型)
* @param3 属性值
*/
let changeStyle = (ele, attr, value) => {
// 注意:这里的 attr 为字符串,如果用.attr 的方式则无用
ele.style[attr] = value;
}
/**
* 随机生成 rgb 颜色
* @param1 最小值
* @param2 最大值
*/
let changeColor = (min, max) => {
r = Math.floor(Math.random() * (max - min) + min);
g = Math.floor(Math.random() * (max - min) + min);
b = Math.floor(Math.random() * (max - min) + min);
return 'rgb('+ r + ',' + g + ',' + b + ')';
}
window.onload = function () {
const buttons = document.querySelectorAll('button');
const divBox = document.querySelector('div');
let changeAttrs = new Array('width', 'height', 'background', 'borderRadius', 'display', 'display');
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function () {
// 当按下重置按钮后将重置样式
i == buttons.length - 1 && (divBox.style.cssText = '');
// 只有当且每次按下变色的时候随机生成颜色
let bgColor = i == 2 ? changeColor(0, 255) : '';
let changValues = new Array('600px', '600px', bgColor, '50%', 'none', 'block');
changeStyle(divBox, changeAttrs[i], changValues[i]);
});
}
}
</script>
</body>
</html>
原文链接:https://www.cnblogs.com/duxiu-fang/p/11122871.html
如有疑问请与原作者联系
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
- 关于jQuery UI 使用心得及技巧 2020-03-29
- js中去掉字串左右空格 2020-03-20
- Js中如何使用sort() 2020-03-18
- 使用JS在浏览器中判断当前网络连接状态的几种方法 2020-03-12
- 在JavaScript中尽可能使用局部变量的原因 2020-03-08
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash
