Div id显示仅在移动检测结果没有使用javascript

Div id display only on If mobile detected results nothing using javsacript

本文关键字:javascript 结果 检测 显示 id 移动 Div      更新时间:2023-09-26

我希望仅在移动设备检测上显示div id。当我在移动设备上测试时,我把警报信息放在手机上,它显示得很好,但div没有显示在移动设备上,只是显示空白屏幕。这是我的代码,请检查我错在哪里。

<html>
<head>
<script>
var isMobile = {
    Android: function() {
        return navigator.userAgent.match(/Android/i);
    },
    BlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i);
    },
    iOS: function() {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    Opera: function() {
        return navigator.userAgent.match(/Opera Mini/i);
    },
    Windows: function() {
        return navigator.userAgent.match(/IEMobile/i);
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
    }
};
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js"></script>
<script>
if(isMobile.any()){
alert('mobile');    
$("#dialog").show();
}
else{
$("#dialog").hide();
}
</script>
</head>    
<body>
<div id="dialog"  style=" display: none"title="Basic dialog">
<p>This is an animated dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
<input class="myInput" type="text" />
<button class="formSaver">Save me!</button>
</div>       
</body>    
</html>

$(document).ready()包装你的代码

$(document).ready(function(){
    if(isMobile.any()){
        alert('mobile');    
        $("#dialog").show();
    }
    else{
      $("#dialog").hide();
    }
})

您需要更新您的脚本如下:使用document ready

<script>
jQuery(document).ready(function(){
    if(isMobile.any()){
       alert('mobile');    
       $("#dialog").show();
    } else {
       $("#dialog").hide();
    }
});
</script>

参考- https://api.jquery.com/ready/

问题出在你的对话框div元素

style=" display: none"