我通过在javascript的帮助下动态添加css样式,使一些气泡随机移动
这里我使用addElement方法添加多个div块。
现在,当我在body中创建一个新元素并尝试使用<style>
元素下没有javaScript的css样式时,它不起作用。
<!DOCTYPE html>
<html>
<head>
<style>
.box {
position: absolute;
width: 100px;
height: 100px;
border-radius: 100px;
box-shadow:0 0 10px #0000e6;
-webkit-transition: 5s linear;
}
.box:hover {
width: 100px;
height: 100px;
border-radius: 100px;
background-color:red;
}
}
.next
{
position: absolute;
border-radius: 10px;
width: 40px;
height: 20px;
box-shadow:0 0 10px #0000e6;
left:500px;
top:400px;
color:white;
}
</style>
</head>
<body bgcolor="black" onload="bbbl()">
<h2 class="next">Next</h2>
<script>
function getRandom(max) {
return Math.random() * (max - 0) + 0;
}
function moveRandom(){
var box = document.getElementsByClassName('box')
for (var i = 0; i < box.length; i++) {
box[i].style.left = (getRandom(window.innerWidth) -100) + 'px';
box[i].style.top = (getRandom(window.innerHeight) -100) + 'px';
}
}
function bbbl() {
for (i = 0; i <= 51; i++) {
var el = document.createElement('div')
el.classList.add('box')
el.style.backgroundColor = "black";
el.style.opacity = "0.9";
document.body.insertBefore(el, document.body.childNodes[0])
moveRandom()
}
}
bbbl()
setInterval(moveRandom, 5000)
</script>
</body>
</html>
&#13;
答案 0 :(得分:0)
<!DOCTYPE html>
<html>
<head>
<style>
.box {
position: absolute;
width: 100px;
height: 100px;
border-radius: 100px;
box-shadow:0 0 10px #0000e6;
-webkit-transition: 5s linear;
}
.box:hover {
width: 100px;
height: 100px;
border-radius: 100px;
background-color:red;
}
} <<<<<<<<<<<<< delete
.next
{
position: absolute;
border-radius: 10px;
width: 40px;
height: 20px;
box-shadow:0 0 10px #0000e6;
left:500px;
top:400px;
color:white;
}
</style>
</head>
<body bgcolor="black" onload="bbbl()">
<h2 class="next">Next</h2>
<script>
function getRandom(max) {
return Math.random() * (max - 0) + 0;
}
function moveRandom(){
var box = document.getElementsByClassName('box')
for (var i = 0; i < box.length; i++) {
box[i].style.left = (getRandom(window.innerWidth) -100) + 'px';
box[i].style.top = (getRandom(window.innerHeight) -100) + 'px';
}
}
function bbbl() {
for (i = 0; i <= 51; i++) {
var el = document.createElement('div')
el.classList.add('box')
el.style.backgroundColor = "black";
el.style.opacity = "0.9";
document.body.insertBefore(el, document.body.childNodes[0])
moveRandom()
}
}
bbbl()
setInterval(moveRandom, 5000)
</script>
</body>
</html>