我有一个div有
.mydiv{
background-color:white;
color:red;
}
.mydiv:hover{
background-color:red;
cursor: pointer;
color:white;
}
我希望在触摸设备上也有类似悬停的特性。我得到的行为并不是我想要的。类似悬停的行为确实会发生,但它是粘性的。我发现如果我添加
.mydiv:active{
background-color:red;
cursor: pointer;
color:white;
}
然后粘性消失了,它按我的意愿工作。但是,正常的悬停行为(在非触摸设备上(会消失(
做这件事的正确方法是什么?
只需使用媒体查询。智能手机的最大量角器模式屏幕宽度为480像素。所以你告诉所有屏幕在480px或低于一个不同的CSS,然后屏幕高于480px。
.mydiv{
background-color:white;
color:red;
}
@media only screen
and (min-width: 481px) {
.mydiv:hover{
background-color:red;
cursor: pointer;
color:white;
}
}
@media only screen
and (max-width: 480px) {
.mydiv:active{
background-color:red;
cursor: pointer;
color:white;
}
}
有一个简单的解决方案。这就是代码!
function myFunction(){
var x = document.getElementById("DIV");
x.style.backgroundColor="red";
x.style.cursor="pointer";
x.style.color="white"
}
function my2Function(){
var x = document.getElementById("DIV");
x.style.backgroundColor="white";
x.style.color="red"
}
.mydiv {
background-color: white;
color: red;
}
.mydiv:active {
background-color: red;
cursor: pointer;
color: white;
}
<div class = "mydiv" id="DIV" onmouseover="myFunction()" onmouseleave="my2Function()">
hi
</div>