[英]how to insert javascript code that is disabled for mobile devices and only works on desktop?
[英]How to run some javascript code only on small screen/mobile devices
我正在構建一個將在所有設備上使用的vue Web應用程序。 我有一些代碼,我想只在小型設備或移動設備上執行。 目前我在$(window).width()
的if條件下有代碼,如下所示:
if ($(window).width() <= 768) {
//My mobile specific code
}
有沒有更好的方法或vue方式這樣做?
編輯
例如,我有一個組件:
export default {
data () {
return {
fade: false,
showFilter: $(window).width() > 768
}
},
components: { PrFilter, Pr },
created () {
if ($(window).width() <= 768) {
bus.$on('pr-changed', () => {
this.showFilter = false
this.fade = false
})
}
}
}
在另一個組件中,我有:
watch: {
matchingPr: function (filteredPr) {
if (filteredPr.length) {
this.pr = filteredPr[0]
if ($(window).width() <= 768) {
bus.$emit('pr-changed')
}
}
}
},
您可以使用
function detectmob() {
if( navigator.userAgent.match(/Android/i)
|| navigator.userAgent.match(/webOS/i)
|| navigator.userAgent.match(/iPhone/i)
|| navigator.userAgent.match(/iPad/i)
|| navigator.userAgent.match(/iPod/i)
|| navigator.userAgent.match(/BlackBerry/i)
|| navigator.userAgent.match(/Windows Phone/i)
){
return true;
}
else {
return false;
}
}
navigator.userAgent方法。
您可以根據需要檢查條件並加載JS。
<script>
if (screen && screen.width > 480) {
document.write('<script type="text/javascript" src="foo.js"><\/script>');
}
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.