2016-12-15 194 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」' –

相關問題