<分区>
标签 javascript html css
所以当我将鼠标悬停在它上面时,我有一个修改 div 背景颜色的转换,如果我按下执行 myFunction2 的按钮,它在悬停在 div 上之前也会更改 div 的背景颜色,那么转换不会再修改背景颜色。
function myFunction2() {
document.getElementById("myDIV").style.backgroundColor = "yellow";
}
function myFunction() { document.getElementById("myDIV").style.WebkitTransition = "all 2s"; // Code for Safari 3.1 to 6.0
document.getElementById("myDIV").style.transition = "all 2s"; // Standard syntax
}
#myDIV {
border: 1px solid black;
background-color: lightblue;
width: 270px;
height: 200px;
overflow: auto;
}
#myDIV:hover {
background-color: coral;
width: 570px;
height: 500px;
padding: 100px;
border-radius: 50px;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Mouse over the DIV element and it will change, both in color and size!</p>
<p>Click the "Try it" button and mouse over the DIV element again. The change will now happen gradually, like an animation:</p>
<button onclick="myFunction2()">Try it2</button><br>
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
<h1>myDIV</h1>
</div>
</body>
</html>
最佳答案
在 myFunction2() 中,你将 div 的背景颜色设置为黄色,这样它就不会改变(即过渡不会再修改背景颜色)
如果你想有过渡,那么通过js本身添加过渡。
演示:
<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
border: 1px solid black;
background-color: lightblue;
width: 270px;
height: 200px;
overflow: auto;
}
#myDIV:hover {
background-color: coral;
width: 570px;
height: 500px;
padding: 100px;
border-radius: 50px;
}
</style>
</head>
<body>
<p>Mouse over the DIV element and it will change, both in color and size!</p>
<p>Click the "Try it" button and mouse over the DIV element again. The change will now happen gradually, like an animation:</p>
<button onclick="myFunction2()">Try it2</button>
<br>
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
<h1>myDIV</h1>
</div>
<script>
function myFunction2()
{
document.getElementById("myDIV").style.backgroundColor = "lightblue";
var css = '#myDIV:hover{ background-color: yellow !important;}';
var style = document.createElement('style');
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
document.getElementsByTagName('head')[0].appendChild(style);
}
function myFunction() {
var css = '#myDIV:hover{ background-color: coral !important;}';
var style = document.createElement('style');
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
document.getElementsByTagName('head')[0].appendChild(style);
document.getElementById("myDIV").style.WebkitTransition = "all 2s"; // Code for Safari 3.1 to 6.0
document.getElementById("myDIV").style.transition = "all 2s"; // Standard syntax
}
</script>
</body>
</html>
关于javascript - 函数执行后 CSS 转换无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59721367/