为移动设备和桌面设备提供不同的内容

serve different content for a mobile device than desktop

本文关键字:移动 桌面      更新时间:2023-09-26

我正在建立一个网站,如果用户在桌面设备上,我希望提供视频,如果在移动设备上,我将提供gif。

有人对这方面的最佳实践有什么指导吗?

下面的代码够吗?当我在chrome上测试这个时,它没有显示移动gif,但也许这里有些不正确。

我应该使用modernizr来覆盖我可能没有意识到的浏览器/设备不一致吗?有没有我应该采取的data-src方法?

<div id="main"></div>
<script type="text/javascript">
var main = document.getElementById('main');
//check if a mobile device
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
   main.innerHTML = '<img src="http://static1.squarespace.com/static/552a5cc4e4b059a56a050501/565f6b57e4b0d9b44ab87107/566024f5e4b0354e5b79dd24/1449141991793/NYCGifathon12.gif>"';
}
else {
    main.innerHTML = '<video width="640" height="360" controls="" autoplay=""><source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" type="video/mp4"><source src="http://clips.vorwaerts-gmbh.de/VfE.webm" type="video/webm"><source src="http://clips.vorwaerts-gmbh.de/VfE.ogv" type="video/ogg"></video>';
}
</script>

请不要测试设备,测试屏幕尺寸。

var windowWidth = $(window).width();
var maxDeviceWidth = 768;
if (windowWidth > maxDeviceWidth) {
    //Server the desktop version
    //You can get the content with Ajax or load both and hide the other
} else {
    //Load the mobile content - either with Ajax, or hide the desktop content
}

我建议您根据屏幕宽度用Ajax加载内容。一定要在

中加上这个
$(window).resize();

确保你考虑到屏幕侧转。

更新:我已经包含了基于innerWidth的动态插入,所以现在应该很酷,它包括宽屏幕上的视频,以及小屏幕上的gif。

HTML:

<div class="wrapper">
    <div id="video-container">
        <video></video>
    </div>
    <div id="gif-container">
        <img src="gif.gif">
    </div>
</div>
CSS:

#video-container {
    display: none;
}
#gif-container {
    display: block;
}
// Mobile first = win!
@media screen and (min-width: 40em) {
    #video-container {
        display: block;
    }
    #gif-container {
        display: none;
    }
}
JavaScript:

function videoOrImage() {
    console.log('hit')
    if(window.innerWidth > 800) {
        document.getElementById('gif-container').innerHTML = ''
        var container = document.getElementById('video-container')
        container.innerHTML = '<video width="320" height="240" controls><source src="movie.mp4" type="video/mp4"><source src="movie.ogg" type="video/ogg">Your browser does not support the video tag.</video>'
    }
    else {
        document.getElementById('video-container').innerHTML = ''
        var container = document.getElementById('gif-container')
        container.innerHTML = '<img src="https://placehold.it/200">';
    }   
}
window.onresize = videoOrImage();
相关文章: