CSS3 transition改变内联样式无效的原因
1.悬浮在元素上面只能改变其字体颜色,但是改变不了背景颜色,原来代码如下
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>changeImage</title>
<style>
#mydiv{
background-color: khaki;
-webkit-transition:color 1s ease-in-out, background-color 0.5s ease-in-out;
-moz-transition:color 1s ease-in-out, background-color 0.5s ease-in-out;
-o-transition:color 1s ease-in-out, background-color 0.5s ease-in-out;
transition:color 1s ease-in-out, background-color 0.5s ease-in-out;
}
#mydiv:hover{
background-color:firebrick;
color: green;
}
</style>
</head>
<body>
<script>
function changeImage(){
element = document.getElementById('myimage');
if(element.src.match("off")){
// 改变元素属性
element.src = "../img/pic_bulb_on.gif";
}else{
element.src = "../img/pic_bulb_off.gif";
}
}
function changediv(){
element = document.getElementById('mydiv');
// 改变元素样式
element.style.width = "400px";
element.style.height = "200px";
element.style.background = "pink";
}
</script>
<img id="myimage" onclick="changeImage()" src="../img/pic_bulb_off.gif" width="100" height="180">
<p>点击灯泡就可以打开或关闭这盏灯</p>
<div id="mydiv" style="border:1px solid black;background-color:lightskyblue;width: 200px;height: 100px;" onclick="changediv()">
hello
</div>
</body>
</html>
作用效果发现只有字体颜色发生变化,背景颜色无法发生改变:
鼠标悬浮之后:
2.去掉background-color:lightskyblue;之后就可以生效了
去掉之后演示结果:
3.原因分析
用transition去改变元素样式时,如果样式是内部样式,则无法实现改变。主要是因为优先级内联样式>内部样式>外部样式。用transition改变属性之后属性仍然在内部样式中,其优先级小于内联样式,所以不会起作用。所以如果想生效,不要写成内联样式。