有一个有背景颜色的div,我们要改变其透明度,要求不能用html和css来实现,只用js该如何实现呢?
一,首先我们先看看用常规的html+css+js的代码
1.html代码:
<body>
<div id="box">
</div>
</body>
2.css代码:
<style type="text/css">
* {
margin: 0;
padding: 0;
}
div {
width: 100px;
height: 100px;
background: deepskyblue;
position: absolute;
left: 200px;
top: 200px;
opacity: 0.3;
}
</style>
3.JavaScript代码:
<script type="text/javascript">
var obj = document.querySelector("div");
obj.onmouseover = function () {
start(100);
}
obj.onmouseout = function () {
start(30);
}
let alpha = 30;
let times = '';
function start(target) {
let speed = target - alpha > 0 ? 1 : -1;
times = setInterval(() => {
alpha += speed;
if (alpha == target) clearInterval(times);
obj.style.opacity = alpha / 100;
}, 30)
}
</script>
二,只用JavaScript实现的代码
<script>
function Box(ele, attr, style, father) {
this.newEle = document.createElement(ele);
this.attr = attr;
this.style = style;
this.father = father || document.body;
this.setAttr();
}
Box.prototype.setAttr = function () {
Object.assign(this.newEle, this.attr);
this.style && this.setStyle();
this.append();
};
Box.prototype.setStyle = function () {
Object.assign(this.newEle.style, this.style);
}
Box.prototype.append = function () {
this.father.appendChild(this.newEle)
}
new Box('div',
{id: 'box'},
{
width: '200px',
height: '200px',
background: 'red',
opacity: '0.3'
});
var boxObj = document.getElementById('box');
let alpha = 30;
let times = '';
function changeAlpha(target) {
let speed = target - alpha > 0 ? 1 : -1;
times = setInterval(() => {
alpha += speed;
if (alpha == target) clearInterval(times);
boxObj.style.opacity = alpha / 100;
}, 30)
}
boxObj.onmouseover = function () {
changeAlpha(100);
}
boxObj.onmouseout = function () {
changeAlpha(30);
}
</script>