iPad/iPhone 호버 문제로 인해 사용자가 링크를 두 번 클릭합니다.
예전에 만든 웹사이트가 있는데, jquery mouse events를 사용합니다.방금 ipad를 받았는데 이벤트 위의 모든 마우스가 클릭으로 번역되는 것을 발견했습니다.그래서 예를 들어 저는 한 번이 아니라 두 번 클릭해야 합니다.(실제 클릭보다 첫 번째 호버)
이 문제를 해결할 수 있는 해결 방법이 있습니까? 아마도 마우스 오버/아웃 등 대신 jquery 명령을 사용했어야 했을 것입니다.감사합니다!
이것을 완전히 테스트하지는 않았지만 iOS가 터치 이벤트를 발생시키기 때문에, 당신이 jQuery 설정에 있다고 가정하면 이것이 작동할 수 있습니다.
$('a').on('click touchend', function(e) {
var el = $(this);
var link = el.attr('href');
window.location = link;
});
가 Mobile WebKit를 입니다.touchend
듣고 를 리디렉션합니다.touchend
링크에서 이벤트가 발생했습니다.
당신의 질문이 무엇인지 완전히 명확하지는 않지만, 마우스에 대한 호버 효과를 유지하면서 더블 클릭을 없애고 싶다면, 제 조언은 다음과 같습니다.
- 에
touchstart
그리고.mouseenter
. - 에서
mouseleave
,touchmove
그리고.click
.
배경
마우스를 시뮬레이션하기 위해 Webkit mobile과 같은 브라우저는 사용자가 iPad와 같은 터치 스크린에서 손가락을 눌렀다가 놓으면 다음 이벤트를 발생시킵니다(소스:html5rocks.com 에서 마우스를 터치합니다):
touchstart
touchmove
touchend
- 300ms 지연, 브라우저가 이중 탭이 아닌 단일 탭인지 확인합니다.
mouseover
mouseenter
- 참고: 만약
mouseover
,mouseenter
또는mousemove
이벤트는 페이지 내용을 변경하며, 다음 이벤트는 실행되지 않습니다.
- 참고: 만약
mousemove
mousedown
mouseup
click
단순히 웹 브라우저에게 마우스 이벤트를 건너뛰라고 말하는 것은 불가능해 보입니다.
더 나쁜 것은, 마우스 오버 이벤트가 페이지 내용을 변경하면 Safari Web Content Guide - Handling Events, 특히 원핑거 이벤트의 그림 6.4에 설명된 바와 같이 클릭 이벤트가 실행되지 않습니다.정확히 "콘텐츠 변경"이 무엇인지는 브라우저와 버전에 따라 달라집니다.iOS 7.0의 경우 배경색 변경이 콘텐츠 변경이 아니라는 것을 알게 되었습니다.
솔루션 설명
요약:
- 에
touchstart
그리고.mouseenter
. - 에서
mouseleave
,touchmove
그리고.click
.
에 대한 작업이 없습니다.touchend
!
이벤트에 : 이은분마이적용에니다됩벤트우스명것.mouseenter
그리고.mouseleave
포함)mouseover
그리고.mouseout
및 합니다.)가 실행되고 호버를 추가 및 제거합니다.
사용자가 실제로click
링크로서 호버 효과도 제거됩니다.이렇게 하면 사용자가 웹 브라우저에서 뒤로 단추를 누를 때 해당 단추가 제거됩니다.
이벤트에 합니다: 이적용됩다니도에벤트이터치기능은:.touchstart
호버 효과가 추가되었습니다.'아니요'가 제거되었습니다.touchend
은 다에시추다니됩가음에 됩니다.mouseenter
그리고 이것은 콘텐츠 변경을 야기하지 않기 때문에 (이미 추가된),click
이벤트도 발생하고 사용자가 다시 클릭할 필요 없이 링크가 따라갑니다!
가 브저가다시사간갖는이 300ms 사이에 touchstart
및 벤트및이click
이 짧은 시간 동안 호버 효과가 표시되기 때문에 실제로 잘 사용됩니다.
사용자가 클릭을 취소하기로 결정한 경우 손가락을 움직이면 정상적으로 취소됩니다.일반적으로 이것은 문제가 됩니다. 왜냐하면 아니오.mouseleave
이벤트가 실행되고 호버 효과가 제자리에 유지됩니다.고맙게도, 이 문제는 호버 효과를 제거하여 쉽게 해결할 수 있습니다.touchmove
.
바로 그거야!
예를 들어 FastClick 라이브러리를 사용하여 300ms 지연을 제거할 수 있지만 이 문제는 범위를 벗어납니다.
대체 솔루션
다음과 같은 대안에서 다음과 같은 문제를 발견했습니다.
- 브라우저 탐지: 오류가 발생하기 매우 쉽습니다.장치에 마우스나 터치 중 하나가 있다고 가정하고, 터치 디스플레이가 확산되면 이 두 가지의 조합이 점점 더 보편화됩니다.
- CSS 미디어 탐지:제가 아는 유일한 CSS 전용 솔루션입니다.여전히 오류가 발생하기 쉬우며 장치에 마우스나 터치가 있다고 가정하지만 둘 다 가능합니다.
- 클릭 이벤트 에뮬레이트: 사용자가 실제로 링크를 클릭하지 않고 스크롤 또는 확대/축소만 원했더라도 링크를 잘못 따라갑니다.
- 변수를 사용하여 마우스 이벤트를 억제합니다.이것은 변수를 설정합니다.
touchend
해당 시점의 상태 변경을 방지하기 위해 이후 마우스 이벤트에서 if 조건으로 사용됩니다.클릭 이벤트에서 변수가 재설정됩니다.터치 인터페이스에 호버 효과가 발생하지 않으려면 이 방법이 적합합니다.불행하게도, 이것은 만약 다음 경우에 작동하지 않습니다.touchend
는 다른 이유로 인해 실행되고 클릭 이벤트가 발생하지 않으며(예: 사용자가 스크롤 또는 확대/축소), 그 후 마우스로 링크를 따라가려고 합니다(예: 마우스와 터치 인터페이스가 모두 있는 장치).
추가 읽기
- http://jsfiddle.net/macfreek/24Z5M/ .이 샌드박스에서 위의 솔루션을 직접 테스트해 보십시오.
- http://www.macfreek.nl/memory/Touch_and_mouse_with_hover_effects_in_a_web_browser .이 답은 조금 더 배경이 있는 것과 같습니다.
- http://www.html5rocks.com/en/mobile/touchandmouse/ .터치와 마우스에 대한 html5rocks.com 의 좋은 배경 기사입니다.
- https://developer.apple.com/library/ios/DOCUMENTATION/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html .Safari Web Content Guide - 이벤트 처리특히 그림 6.4를 참조하십시오. 이는 다음 기간 동안 콘텐츠 변경 후 추가 이벤트가 발생하지 않음을 설명합니다.
mouseover
또는mousemove
이벤트
iPad/iPhone 더블 클릭 문제 및 모바일 브라우저에서 호버 효과 사용 안 함을 참조하십시오.
결국 CSS 솔루션이 있는 것 같습니다.Safari가 두 번째 터치를 기다리는 이유는 :hover 이벤트에서 일반적으로 할당하는 배경 이미지(또는 요소) 때문입니다.보여줄 것이 없다면 문제가 없을 것입니다.솔루션은 보조 CSS 파일(또는 JS 접근 방식의 경우 스타일)로 iOS 플랫폼을 대상으로 하여 예를 들어 배경을 상속하고 마우스에 표시할 요소를 숨깁니다.
다음은 CSS와 HTML의 예입니다. 마우스 위에 별표가 있는 제품 블록입니다.
HTML:
<a href="#" class="s"><span class="s-star"></span>Some text here</a>
CSS:
.s {
background: url(some-image.png) no-repeat 0 0;
}
.s:hover {
background: url(some-image-r.png) no-repeat 0 0;
}
.s-star {
background: url(star.png) no-repeat 0 0;
height: 56px;
position: absolute;
width: 72px;
display:none;
}
.s:hover .s-star {
display:block;
}
솔루션(보조 CSS):
/* CSS */
/* Keep hovers the same or hidden */
.s:hover {
background:inherit;
}
.s:hover .s-star {
display:none;
}
너무 복잡하게 만들 필요가 없습니다.
$('a').on('touchend', function() {
$(this).click();
});
저에게 효과가 있었던 것은 여기 있는 다른 사람들이 이미 말한 것입니다.
마우스 이동 또는 마우스 이동 시 요소를 표시/숨기지 않습니다(이 경우 이벤트).
Apple은 다음과 같이 말합니다(https://developer.apple.com/library/content/documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html) :
클릭 가능한 요소는 링크, 폼 요소, 이미지 맵 영역 또는 마우스를 아래로 이동하거나 마우스를 위로 이동하거나 마우스를 위로 이동하거나 클릭할 수 있는 핸들러가 있는 기타 요소입니다.
사용자가 클릭 가능한 요소를 누르면 이벤트가 마우스 오버, 마우스 이동, 마우스 다운, 마우스 업, 클릭 순으로 도착합니다.또한, 페이지 내용이 마우스 이동 이벤트에서 변경되는 경우, 후속 이벤트는 전송되지 않습니다.이 동작을 통해 사용자는 새 콘텐츠를 탭할 수 있습니다.
따라서 @woop의 솔루션을 사용할 수 있습니다. userAgent를 탐지하고, iOS 장치인지 확인한 다음 이벤트를 바인딩합니다.이 기술은 제 요구에 적합하고 원하지 않을 때 호버 이벤트를 바인딩하지 않는 것이 더 이치에 맞기 때문에 사용하게 되었습니다.
하지만... 만약 당신이 userAgents를 엉망으로 만들고 싶지 않다면, 나는 당신이 다음과 같은 네이티브 자바스크립트를 사용하여 요소를 숨기거나 표시할 수 있다는 것을 알게 되었습니다.
$("body").on("mouseover", function() {
document.getElementsByTagName("my-class")[0].style.display = 'block'; //show element
document.querySelector(".my-selector div").style.display = 'none'; // hide element
});
데스크톱 버전에서는 작동하지만 모바일 버전에서는 작동하지 않습니다.
그리고 좀 더 호환성을 위해...
$("body").on("mouseover", function() {
if (document.getElementsByTagName && document.querySelector) { // check compatibility
document.getElementsByTagName("my-class")[0].style.display = 'block'; //show element
document.querySelector(".my-selector div").style.display = 'none'; // hide element
} else {
$(".my-class").show();
$(".my-selector div").hide();
}
});
제 생각에 시도해 보는 것이 현명할 것 같습니다.mouseenter
신에를 mouseover
에 바인딩할 때 내부적으로 사용되는 것입니다..hover(fn,fn)
그리고 일반적으로 당신이 원하는 것입니다.
cduruk의 솔루션은 꽤 효과적이었지만, 제 사이트의 일부에서 문제를 일으켰습니다.제가 이미 JQuery를 사용하여 CSS 호버 클래스를 추가하고 있었기 때문에 가장 쉬운 해결책은 단순히 모바일 장치에 CSS 호버 클래스를 추가하지 않는 것이었습니다.
일반적인 아이디어는 다음과 같습니다.
var device = navigator.userAgent.toLowerCase();
var ios = device.match(/(iphone|ipod|ipad)/);
if (!(ios)) {
$(".portfolio-style").hover(
function(){
$(this).stop().animate({opacity: 1}, 100);
$(this).addClass("portfolio-red-text");
},
function(){
$(this).stop().animate({opacity: 0.85}, 100);
$(this).removeClass("portfolio-red-text");
}
);
}
*설명 목적으로 코드 축소
저는 기존 솔루션에 다음과 같은 문제가 있었고, 이 모든 것을 해결할 수 있는 것을 발견했습니다.이것은 사용자가 브라우저와 장치를 넘나들며 장치 스니핑을 원하지 않는 것을 목표로 한다고 가정합니다.
이것이 해결하는 문제들
만 touchstart
또는touchend
:
- 사람들이 내용을 스크롤하려고 할 때 이벤트가 발생하고 스와이프를 시작할 때 우연히 이 요소를 손가락으로 가리켰습니다. 예기치 않게 액션이 트리거됩니다.
- 데스크톱에서 마우스 오른쪽 버튼을 클릭하는 것과 유사하게 길게 누르면 이벤트가 발생할 수 있습니다.예를 들어 클릭 이벤트가 URL X로 이동하고 사용자가 길게 눌러 새 탭에서 X를 열면 두 탭 모두에서 X가 열려 있는 것을 알 수 없습니다.일부 브라우저(예: iPhone)에서는 길게 누르기 메뉴가 나타나지 않을 수도 있습니다.
트링mouseover
에한사건에 있는 touchstart
그리고.mouseout
touchmove
심각한 결과는 덜하지만 다음과 같은 일반적인 브라우저 동작을 방해합니다.
- 길게 누르면 마우스가 끝이 없습니다.
- 는 은Android ▁on▁의 위치를 처리합니다.
touchstart
좋아해를mouseover
,어느 것이mouseout
음다번에.touchstart
따라서 Android에서 마우스 오버 콘텐츠를 보는 한 가지 방법은 관심 영역을 터치하고 손가락을 움직여 페이지를 살짝 스크롤하는 것입니다. 료치touchmove
~하듯이mouseout
이것을 깨뜨립니다.
해결책
이론적으로, 당신은 단지 다음과 같은 플래그를 추가할 수 있습니다.touchmove
하지만 아이폰은 움직임이 없어도 터치 동작을 트리거합니다.이론적으로, 당신은 단지 비교할 수 있습니다.touchstart
그리고.touchend
벤트이pageX
그리고.pageY
하지만 아이폰에는, 또는가 없습니다pageX
.
그래서 불행하게도 모든 기반을 커버하는 것은 결국 조금 더 복잡해집니다.
$el.on('touchstart', function(e){
$el.data('tstartE', e);
if(event.originalEvent.targetTouches){
// store values, not reference, since touch obj will change
var touch = e.originalEvent.targetTouches[0];
$el.data('tstartT',{ clientX: touch.clientX, clientY: touch.clientY } );
}
});
$el.on('touchmove', function(e){
if(event.originalEvent.targetTouches){
$el.data('tstartM', event.originalEvent.targetTouches[0]);
}
});
$el.on('click touchend', function(e){
var oldE = $el.data('tstartE');
if( oldE && oldE.timeStamp + 1000 < e.timeStamp ) {
$el.data('tstartE',false);
return;
}
if( $el.data('iosTouchM') && $el.data('tstartT') ){
var start = $el.data('tstartT'), end = $el.data('tstartM');
if( start.clientX != end.clientX || start.clientY != end.clientY ){
$el.data('tstartT', false);
$el.data('tstartM', false);
$el.data('tstartE',false);
return;
}
}
$el.data('tstartE',false);
이론적으로는 1000을 근사치로 사용하는 대신 긴 프레스에 사용되는 정확한 시간을 얻는 방법이 있지만, 실제로는 그렇게 간단하지 않고 합리적인 프록시를 사용하는 것이 가장 좋습니다.
맥프리크의 답변은 저에게 매우 도움이 되었습니다.도움이 될 경우를 대비해 몇 가지 실습 코드가 있습니다.
문제 - 터치엔드를 적용하면 요소 위로 손가락을 스크롤할 때마다 마치 누른 것처럼 반응합니다. 단지 스크롤을 지나치려고 할 때에도 마찬가지입니다.
jQuery를 사용하여 일부 버튼 아래에 있는 선을 페이드업하여 호버된 버튼을 "강조"하는 효과를 만들고 있습니다.저는 이것이 링크를 따라가기 위해 터치 장치에서 버튼을 두 번 눌러야 한다는 것을 의미하는 것을 원하지 않습니다.
버튼은 다음과 같습니다.
<a class="menu_button" href="#">
<div class="menu_underline"></div>
</a>
저는 "메뉴_언더라인" div가 마우스 오버 시 페이드 업되고 마우스 아웃 시 페이드 아웃이 되기를 원합니다.하지만 저는 터치 장치가 두 번이 아니라 한 번의 클릭으로 링크를 추적할 수 있기를 원합니다.
솔루션 - 다음은 작동을 위한 jQuery입니다.
//Mouse Enter
$('.menu_button').bind('touchstart mouseenter', function(){
$(this).find(".menu_underline").fadeIn();
});
//Mouse Out
$('.menu_button').bind('mouseleave touchmove click', function(){
$(this).find(".menu_underline").fadeOut();
});
이 MacFreak에 대한 당신의 도움에 감사드립니다.
왜 그런지 묻지 말고 빈 청취기를 추가하면 된다는 것을 방금 알았지만, iOS 9.3.2가 탑재된 아이폰과 아이패드에서 테스트해보니 잘 작동했습니다.
if(/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream){
var elements = document.getElementsByTagName('a');
for(var i = 0; i < elements.length; i++){
elements[i].addEventListener('touchend',function(){});
}
}
나는 당신의 링크가 마우스 오버에서 1번 탭이 활성화되고 더블 탭이 링크를 활성화하는 온마우스 오버 이벤트가 없다고 "생각"합니다. 하지만 idk.저는 아이패드가 없어요.제스처/터치 이벤트를 사용해야 할 것 같습니다.
https://developer.apple.com/documentation/webkitjs
저도 같은 문제가 있었지만 터치 장치에는 문제가 없었습니다.클릭할 때마다 이벤트가 트리거됩니다.이벤트 큐잉 등에 대한 내용이 있습니다.
하지만 제 솔루션은 다음과 같았습니다.클릭 시 이벤트(또는 터치?)당신은 타이머를 설정합니다.XMS 내에서 링크를 다시 클릭하면 false가 반환됩니다.
요소별 타이머를 설정하려면 다음을 사용합니다.$.data()
.
이것은 또한 위에서 설명한 @Ferdy 문제를 해결할 수 있습니다.
Modernizr을 사용하면 Modernizr을 사용하기가 매우 쉽습니다.앞서 언급한 바와 같이 터치합니다.
하지만 저는 모데니즈를 조합해서 사용하는 것을 선호합니다.안전을 위해 터치 및 사용자 에이전트 테스트.
var deviceAgent = navigator.userAgent.toLowerCase();
var isTouchDevice = Modernizr.touch ||
(deviceAgent.match(/(iphone|ipod|ipad)/) ||
deviceAgent.match(/(android)/) ||
deviceAgent.match(/(iemobile)/) ||
deviceAgent.match(/iphone/i) ||
deviceAgent.match(/ipad/i) ||
deviceAgent.match(/ipod/i) ||
deviceAgent.match(/blackberry/i) ||
deviceAgent.match(/bada/i));
function Tipsy(element, options) {
this.$element = $(element);
this.options = options;
this.enabled = !isTouchDevice;
this.fixTitle();
};
를 간단히 대체할 수 .Modernizr.touch
와 상부의 기능을 하는.('ontouchstart' in document.documentElement)
또한 사용자 에이전트 모바일을 테스트하면 Windows Phone보다 더 광범위하게 탐지된 Microsoft 모바일 장치를 사용할 수 있습니다.
사용할 수 있습니다.click touchend
,
예:
$('a').on('click touchend', function() {
var linkToAffect = $(this);
var linkToAffectHref = linkToAffect.attr('href');
window.location = linkToAffectHref;
});
위의 예는 터치 장치의 모든 링크에 영향을 미칩니다.
특정 링크만 대상으로 지정하려면 해당 링크에 클래스를 설정하여 이 작업을 수행할 수 있습니다.
HTML:
<a href="example.html" class="prevent-extra-click">Prevent extra click on touch device</a>
질문:
$('a.prevent-extra-click').on('click touchend', function() {
var linkToAffect = $(this);
var linkToAffectHref = linkToAffect.attr('href');
window.location = linkToAffectHref;
});
건배.
여린
저는 이벤트가 요소의 마우스 엔터/마우스 탈퇴/클릭 상태에 바인딩된 유사한 상황에 부딪혔지만 아이폰에서는 사용자가 요소를 두 번 클릭하여 먼저 마우스 엔터 이벤트를 트리거한 다음 다시 클릭 이벤트를 실행해야 했습니다.
위와 유사한 방법으로 해결했지만 jQuery $.browser 플러그인(jQuery 1.9>용)을 사용하여 다음과 같이 .trigger 이벤트를 mouseenter 바인딩 이벤트에 추가했습니다.
// mouseenter event
$('.element').on( "mouseenter", function() {
// insert mouseenter events below
// double click fix for iOS and mouseenter events
if ($.browser.iphone || $.browser.ipad) $(this).trigger('click');
});
// mouseleave event
$('.element').on( "mouseleave", function() {
// insert mouseout events below
});
// onclick event
$('.element').on( "click", function() {
// insert click events below
});
.trigger는 iPhone 또는 iPad에서 볼 때 요소의 마우스 입력(또는 초기 클릭) 시 .click 이벤트 핸들러를 실행하여 요소를 두 번 클릭할 필요를 방지합니다.가장 우아한 솔루션은 아닐 수도 있지만, 제 경우에는 잘 작동하고 이미 설치되어 있던 플러그인을 활용하기 때문에 이러한 장치에서 기존 이벤트를 작동하려면 코드 한 줄을 추가해야 했습니다.
jQuery $.dll 플러그인은 https://github.com/gabceb/jquery-browser-plugin 에서 구할 수 있습니다.
실수로 링크에서 손가락을 미끄러뜨렸을 때 리디렉션을 방지하기 위한 개선 사항입니다.
// tablet "one touch (click)" X "hover" > link redirection
$('a').on('touchmove touchend', function(e) {
// if touchmove>touchend, set the data() for this element to true. then leave touchmove & let touchend fail(data=true) redirection
if (e.type == 'touchmove') {
$.data(this, "touchmove_cancel_redirection", true );
return;
}
// if it's a simple touchend, data() for this element doesn't exist.
if (e.type == 'touchend' && !$.data(this, "touchmove_cancel_redirection")) {
var el = $(this);
var link = el.attr('href');
window.location = link;
}
// if touchmove>touchend, to be redirected on a future simple touchend for this element
$.data(this, "touchmove_cancel_redirection", false );
});
MacFreak에서 영감을 얻어 저에게 맞는 것을 만들었습니다.
이 js 방법은 ipad에서 호버가 고착되는 것을 방지하고 경우에 따라 클릭이 두 번 클릭으로 등록되지 않도록 합니다.CSS에서 CSS에 :hoverpsudo 클래스가 있으면 .hover로 변경합니다. 예를 들어 .some-class:hover를 .some-class.hover로 변경합니다.
ipad에서 이 코드를 테스트하여 CSS와 js 호버 방법이 어떻게 다르게 동작하는지 확인합니다(호버 효과에서만).CSS 버튼에는 화려한 클릭 경보가 없습니다.http://jsfiddle.net/bensontrent/ctgr6stm/
function clicker(id, doStuff) {
id.on('touchstart', function(e) {
id.addClass('hover');
}).on('touchmove', function(e) {
id.removeClass('hover');
}).mouseenter(function(e) {
id.addClass('hover');
}).mouseleave(function(e) {
id.removeClass('hover');
}).click(function(e) {
id.removeClass('hover');
//It's clicked. Do Something
doStuff(id);
});
}
function doStuff(id) {
//Do Stuff
$('#clicked-alert').fadeIn(function() {
$(this).fadeOut();
});
}
clicker($('#unique-id'), doStuff);
button {
display: block;
margin: 20px;
padding: 10px;
-webkit-appearance: none;
touch-action: manipulation;
}
.hover {
background: yellow;
}
.btn:active {
background: red;
}
.cssonly:hover {
background: yellow;
}
.cssonly:active {
background: red;
}
#clicked-alert {
display: none;
}
<button id="unique-id" class="btn">JS Hover for Mobile devices<span id="clicked-alert"> Clicked</span>
</button>
<button class="cssonly">CSS Only Button</button>
<br>This js method prevents hover from sticking on an ipad, and prevents the click registering as two clicks. In CSS, if you have any :hover in your css, change them to .hover For example .some-class:hover to .some-class.hover
터치 스크롤을 끊지 않고 링크가 작동하도록 하기 위해 jQuery Mobile의 "탭" 이벤트로 이 문제를 해결했습니다.
$('a').not('nav.navbar a').on("tap", function () {
var link = $(this).attr('href');
if (typeof link !== 'undefined') {
window.location = link;
}
});
제가 너무 늦었다는 것은 알지만, 이것이 제가 찾은 가장 쉬운 해결책 중 하나입니다.
$('body').on('touchstart','*',function(){ //listen to touch
var jQueryElement=$(this);
var element = jQueryElement.get(0); // find tapped HTML element
if(!element.click){
var eventObj = document.createEvent('MouseEvents');
eventObj.initEvent('click',true,true);
element.dispatchEvent(eventObj);
}
});
이것은 링크(앵커 태그)뿐만 아니라 다른 요소에도 적용됩니다.이게 도움이 되길 바랍니다.
이 짧은 토막글은 효과가 있는 것 같습니다.링크를 누를 때 클릭 이벤트를 트리거합니다.
$('a').on('touchstart', function() {
$(this).trigger('click');
});
다른 답은 하나도 저에게 맞지 않습니다.내 앱에는 많은 이벤트 청취자, 소유 확인란 및 청취자가 없는 청취자 및 링크가 있는 링크가 있습니다.
사용자:
var selector = "label, a, button";
var timer;
var startX;
var startY;
$(document).on("click", selector, function (e) {
if ($(this).data("touched") === true) {
e.stopImmediatePropagation();
return false;
}
return;
}).on("touchend", selector, function (e) {
if (Math.abs(startX - e.originalEvent.changedTouches[0].screenX) > 10 || Math.abs(startY - e.originalEvent.changedTouches[0].screenY) > 10)
// user action is not a tap
return;
var $this = $(this);
// Visit: http://stackoverflow.com/questions/1694595/can-i-call-jquery-click-to-follow-an-a-link-if-i-havent-bound-an-event-hand/12801548#12801548
this.click();
// prevents double click
$this.data("touched", true);
if (timer)
clearTimeout(timer);
setTimeout(function () {
$this.data("touched", false);
}, 400);
e.stopImmediatePropagation();
return false;
}).on("touchstart", function (e) {
startX = e.originalEvent.changedTouches[0].screenX;
startY = e.originalEvent.changedTouches[0].screenY;
});
이것은 당신이 jquery ui 드롭다운을 가지고 있을 때 나에게 효과가 있습니다.
if (navigator.userAgent.match(/(iPod|iPhone|iPad)/)) {
$('.ui-autocomplete').off('menufocus hover mouseover');
}
호버 CSS 이벤트 내부의 "표시" 스타일을 변경하지 않도록 합니다.저는 "디스플레이: 블록"을 호버 상태로 유지했습니다.ios를 제거한 후 한 번 탭으로 연결되었습니다.그런데 최신 IOS 업데이트가 이 "기능"을 수정한 것 같습니다.
더블 을 해결하는 은 미디어 입니다.@media (pointer: fine)
:
@media (pointer: fine) {
a span {
display: none;
}
a:hover span {
display: inline-block;
}
}
이 미디어 쿼리로 묶인 CSS는 데스크톱에만 적용됩니다.
이 솔루션에 대한 설명은 여기에 있습니다. https://css-tricks.com/annoying-mobile-double-tap-link-issue/
맥프리크의 답변 덕분에 이 해결책을 생각해냈습니다.클릭 이벤트가 발생하지 않는 연속적으로 마우스 이동 이벤트가 두 개씩 있는 것을 발견했을 때 조금 더 발전했습니다.
(function () {
//https://stackoverflow.com/a/42162450/3717718
function isIosSafari() {
var ua = (window.navigator && navigator.userAgent) || '';
var iOS = !!ua.match(/iPad/i) || !!ua.match(/iPhone/i);
var webkit = !!ua.match(/WebKit/i);
var iOSSafari = iOS && webkit && !ua.match(/CriOS/i);
return iOSSafari;
}
(function removeHoverIosSafari() {
if (!isIosSafari()) return;
// Tags of interest
function shouldPrevent(target) {
var tagName = target.tagName.toLowerCase();
var datasetBind = target.dataset.bind;
var preventFilter = (datasetBind && datasetBind.indexOf('click') > -1) || (tagName == 'a' || tagName == 'button');
return preventFilter;
}
var eventSelector = {
touchend: function (_, target) {
// Reset on touchend
target.dataset._clicked_ = '';
target.dataset._mousemove_ = '0';
target.dataset._timeOutId_ = '';
},
mouseover: function (e) {
e.preventDefault();
},
mousemove: function (e, target) {
e.preventDefault();
var _mousemoves = +(target.dataset._mousemove_ || '0');
_mousemoves = _mousemoves + 1;
console.log('mousemoves: ' + _mousemoves);
target.dataset._mousemove_ = _mousemoves;
if (_mousemoves > 1 && !target.dataset._timeOutId_) {
var id = setTimeout(function () {
console.log('double mousemove click fired');
target.click();
}, 80); // 80ms worked for me, could probably be lower
target.dataset._timeOutId_ = id;
}
},
click: function (e, target) {
if (target.dataset._clicked_) {
console.log('prevented doubleclick');
e.preventDefault();
return;
}
// prevent timeout click
if (target.dataset._timeOutId_) {
console.log('cleared timeout');
clearTimeout(+target.dataset._timeOutId_);
}
// mark element as clicked
target.dataset._clicked_ = 'true';
}
}
function preventHover(e) {
var target = e.target;
//There is no point in continuing if the item for unknown reasons doesnt't have a clickFunction, tagName or dataset (DOMStringMap)
if (!(target && target.click && target.tagName && target.dataset)) return;
if (!shouldPrevent(target)) return;
var type = e.type;
console.log(type, target);
eventSelector[type] && eventSelector[type](e, target);
}
document.addEventListener('touchend', preventHover, true);
document.addEventListener('mouseover', preventHover, true);
document.addEventListener('mousemove', preventHover, true);
document.addEventListener('click', preventHover, true);
})();
})();
확할수있다니를 확인하실 수 .navigator.userAgent
다음과 같이:
if(!navigator.userAgent.match(/iPhone/i) || !navigator.userAgent.match(/iPad/i)) {
//bind your mouseovers...
}
하지만 블랙베리, 드로이드, 기타 터치스크린 장치는 없는지 확인해야 합니다.또한 userAgent에 Mozilla, IE, Webkit 또는 Opera가 포함된 경우에만 마우스를 바인딩할 수 있지만 Droid가 다음과 같이 userAgent 문자열을 보고하므로 일부 장치를 선별해야 합니다.
Mozilla/5.0 (Linux; U; Android 2.0.1; en-us; Droid Build/ESD56) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17
아이폰의 끈도 비슷합니다.iPhone, iPod, iPad, Android 및 Blackberry를 선별하기만 하면 대부분의 핸드헬드를 얻을 수 있지만 일부는 그렇지 않습니다.
태블릿과 모바일 기기를 제외한 CSS 미디어 쿼리를 만들고 거기에 호버를 넣기만 하면 됩니다.이를 위해 jQuery나 JavaScript가 필요하지 않습니다.
@media screen and (min-device-width:1024px) {
your-element:hover {
/* Do whatever here */
}
}
그리고 이것을 HTML 헤드에 추가하여 해상도가 아닌 실제 픽셀로 계산하는지 확인하십시오.
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
언급URL : https://stackoverflow.com/questions/3038898/ipad-iphone-hover-problem-causes-the-user-to-double-click-a-link
'it-source' 카테고리의 다른 글
엔티티 개체를 저장소에서 노출해야 합니까? (0) | 2023.08.04 |
---|---|
jQuery를 사용하여 한 부모에서 다른 부모로 자식 요소를 이동하는 방법 (0) | 2023.08.04 |
개발 및 프로덕션 데이터베이스 동기화 방법 (0) | 2023.07.30 |
aspnet core api에서 Created(또는 CreatedAtAction/CreatedAtRoute)를 사용하는 방법 (0) | 2023.07.30 |
뷰 열에 인덱스를 만들 수 있습니까? (0) | 2023.07.30 |