我正在使用下面的脚本将类“ hover”添加到具有“ reveal-area”类的div中。
jQuery(document).ready(function(){
$(".reveal-area").hover(
function () {
$(this).addClass("reveal-show");
},
function () {
$(this).removeClass("reveal-show");
}
);
});
这在PC上可以正常工作-但是如何在移动设备上添加包括触摸激活(以添加类)的功能?谢谢
最佳答案
我想你需要这样的东西
(function ($) {
'use strict';
$(document).ready(function() {
//check device type
function deviceType() {
var mobile = false;
//touch on IOS and Android
var isAndroid = /(android)/i.test(navigator.userAgent);
var isMobile = /(mobile)/i.test(navigator.userAgent);
if (navigator.userAgent.match(/(iPod|iPhone|iPad)/) || isAndroid || isMobile) {
mobile = true;
}else {
mobile = false;
}
return mobile;
}
//desktop hover
function itemHover() {
$(".reveal-area").hover (
function () {
$(this).addClass("reveal-show");
},
function () {
$(this).removeClass("reveal-show");
}
);
}
//mobile touch
function itemTouch() {
$(".reveal-area").on("touchstart", function () {
$(".reveal-area").removeClass('reveal-show');
$(this).addClass("reveal-show");
//if you need working links comment this
return false;
});
}
function itemInit() {
var mobile = deviceType();
//check device type
if(mobile == true) {
//if mobile
itemTouch();
} else {
//if desktop
itemHover();
}
}
//call function
itemInit();
});
}(jQuery));
.reveal-area {
background: #000;
width: 100%;
height: 200px;
}
.reveal-show {
background: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="hero-item">
<div class="img-area">
<img src="image.jpg" alt="image alt"></div>
<div class="reveal-area">
<img src="link-here.png" class="reveal-button">
<a href="/marine/" class="link-here">Text here...</a>
<a href="/marine/" class="reveal-but">Learn more</a>
</div> <!-- end reveal-area -->
<div class="reveal-area">
<img src="link-here.png" class="reveal-button">
<a href="/marine/" class="link-here">Text here...</a>
<a href="/marine/" class="reveal-but">Learn more</a>
</div> <!-- end reveal-area -->
</div> <!-- end hero item 1-->
</div>
<div class="hero-item">
<div class="img-area">
<img src="image.jpg" alt="image alt"></div>
<div class="reveal-area">
<img src="link-here.png" class="reveal-button">
<a href="/marine/" class="link-here">Text here...</a>
<a href="/marine/" class="reveal-but">Learn more</a>
</div> <!-- end reveal-area -->
<div class="reveal-area">
<img src="link-here.png" class="reveal-button">
<a href="/marine/" class="link-here">Text here...</a>
<a href="/marine/" class="reveal-but">Learn more</a>
</div> <!-- end reveal-area -->
</div> <!-- end hero item 1-->
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>