2016-12-15 193 views
1

我想在我的页面顶部添加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> 
+0

您无法在JavaScript中编写HTML标签。请参阅@Yusaf Khaliq答案。 –

回答

1

如果我理解正确,您希望显示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块之外,例如,

+0

如何设置的hieght和宽度老板 –

+0

我怎么也加链接图片src –

+0

变化'img.src =“链接的形象在这里”';和'image.style.width =“100px”' –

相关问题