請詳解移動端點透费韭,為什么會發(fā)生點透茧球?描述發(fā)生的場景及解決方案
什么是點擊穿透?
假如頁面上有兩個元素A和B星持。B元素在A元素之上抢埋。我們在B元素的touchstart事件上注冊了一個回調(diào)函數(shù),該回調(diào)函數(shù)的作用是隱藏B元素督暂。我們發(fā)現(xiàn)揪垄,當我們點擊B元素,B元素被隱藏了逻翁,隨后饥努,A元素觸發(fā)了click事件。
這是因為在移動端瀏覽器八回,事件執(zhí)行的順序是touchstart > touchend > click酷愧。而click事件有300ms的延遲,當touchstart事件把B元素隱藏之后缠诅,隔了300ms溶浴,瀏覽器觸發(fā)了click事件,但是此時B元素不見了管引,所以該事件被派發(fā)到了A元素身上士败。如果A元素是一個鏈接,那此時頁面就會意外地跳轉(zhuǎn),input汉匙,select會吊起鍵盤拱烁。
點透的解決方法:
方案一:來得很直接github上有個fastclick可以完美解決
引入fastclick.js生蚁,因為fastclick源碼不依賴其他庫所以你可以在原生的js前直接加上
window.addEventListener( "load", function() {
? ? FastClick.attach( document.body );
}, false );
或者有zepto或者jqm的js里面加上
$(function() {
? ? FastClick.attach(document.body);
});
當然require的話就這樣:
var FastClick = require('fastclick');
FastClick.attach(document.body, options);
方案二:用touchend代替tap事件并阻止掉touchend的默認行為preventDefault()
$("#cbFinish").on("touchend", function (event) {
? //很多處理比如隱藏什么的? ? event.preventDefault();
});
方案三:延遲一定的時間(300ms+)來處理事件
$("#cbFinish").on("tap", function (event) {
? ? setTimeout(function(){
? ? //很多處理比如隱藏什么的? ? },320);
});
移動端為什么會有一像素問題?如何解決戏自?
由于分辨率 DPI 的差異邦投,高清手機屏上的 1px 實際上是由 2×2 個像素點來渲染,有的屏幕甚至用到了 3×3 個像素點
所以在實際的代碼實現(xiàn)中擅笔,設(shè)置1px的邊框志衣,會渲染成2px.
一、使用transform: scale
先使用偽類 :after 或者 :before 創(chuàng)建 1px 的邊框猛们,然后通過 media 適配不同的設(shè)備像素比念脯,然后調(diào)整縮放比例,從而實現(xiàn)一像素邊框
.border-bottom{
? ? position: relative;
}
.border-bottom::after {
? ? content: " ";
? ? position: absolute;
? ? left: 0;
? ? bottom: 0;
? ? width: 100%;
? ? height: 1px;
? ? background-color: #e4e4e4;
? ? -webkit-transform-origin: left bottom;
? ? transform-origin: left bottom;
}
然后通過媒體查詢來適配
/* 2倍屏 */
@media only screen and (-webkit-min-device-pixel-ratio: 2.0) {
? ? .border-bottom::after {
? ? ? ? -webkit-transform: scaleY(0.5);
? ? ? ? transform: scaleY(0.5);
? ? }
}
/* 3倍屏 */
@media only screen and (-webkit-min-device-pixel-ratio: 3.0) {
? ? .border-bottom::after {
? ? ? ? -webkit-transform: scaleY(0.33);
? ? ? ? transform: scaleY(0.33);
? ? }
}
或者弯淘,直接rem設(shè)置绿店。