我正在尝试在页面顶部添加 JavaScript,如果它检测到移动浏览器,那么我的 html 代码将使用适当的 html 代码和图像高度和宽度设置。
<script type="text/javascript">
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) )
<img src="https://drive.google.com/uc?export=view&id=0B2VHnnIsISjHdWRLVk9zS2VuUFk" alt="" style="width:1904px;height:328px;">
else
<img src="https://drive.google.com/uc?export=view&id=0B2VHnnIsISjHdWRLVk9zS2VuUFk" alt="" style="width:1904px;height:528px;">
</script>
我不确定为什么它不起作用?
我如何用完整的 JavaScript 实现这个
var img = document.createElement("img");
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
img.src = "http://home.bt.com/images/the-iphone-7-and-7-plus-which-bt-mobile-plan-is-right-for-me-136409622203503901-160915131847.jpg";
img.style.width = "648px";
img.style.height = "365px";
} else {
img.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d7/Desktop_computer_clipart_-_Yellow_theme.svg/281px-Desktop_computer_clipart_-_Yellow_theme.svg.png";
img.style.width = "281px";
img.style.height = "203px";
}
document.body.appendChild(img);
所以它在
<script type="text/javascript">
一些代码
喜欢这个完整的代码,这样我就可以将它添加到我的 html 代码中
编辑了新内容
这是正确的吗?
<script type="text/javascript">
var img = document.createElement("img");
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
img.src = "https://drive.google.com/uc?export=view&id=0B2VHnnIsISjHdWRLVk9zS2VuUFk";
img.style.width = "1904px";
img.style.height = "365px";
} else {
img.src = "https://drive.google.com/uc?export=view&id=0B2VHnnIsISjHdWRLVk9zS2VuUFk";
img.style.width = "1904px";
img.style.height = "403px";
}
document.body.appendChild(img);
</script>
最佳答案
如果我理解正确的话,您想要显示 2 张图像中的 1 张,具体取决于用户使用的是移动设备还是计算机。 (顺便说一句,我还没有测试过你的测试功能)
<script type="text/javascript">
var img = document.createElement("img");
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
img.src = src;
img.style.width = width;
img.style.height = height;
}
else{
img.src = src;
img.style.width = width;
img.style.height = height;
}
document.body.appendChild(img);
</script>
首先,您可以创建图像节点,设置 src 高度和宽度,然后附加到正文。还有空间可以清理我在示例中使用的代码。例如,在 if else block 之外设置样式宽度和高度
关于javascript - 如何为移动和桌面浏览器创建两个不同的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41174457/