使用svg让页面自适应浏览器大小,整体等比缩放

mapaler 2019-12-23

网页代码:

<!DOCTYPE html>
<html>
<head>
<style>
body
{
margin:0;
padding:0;
width:100%;
height:100%;
background-color: #282828;
}

/*自定义悬浮菜单中滚动条*/

::-webkit-scrollbar-button {
    display: none;
}

::-webkit-scrollbar-track {
    background-color: #eaeaea;
    border-left: 1px solid #cecece;
    border-radius: 5px;
    box-shadow: none;
    border: 0;
}

::-webkit-scrollbar {
    width: 5px;
    height: 5px;
}

::-webkit-scrollbar-thumb {
    background-color: #cecece;
    border-radius: 5px;
    box-shadow: none;
    border: 0;
}

::-webkit-scrollbar-thumb:hover {
    background-color: #aaa;
}

</style>
</head>
<body>
  <svg id="main" style="margin: 0px; overflow: hidden;" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"  data-version="v6.5.36" preserveAspectRatio="xMinYMin meet" viewBox="0 0 1452 860" width="1452" height="860"><image xlink:href="./jxsbback.png" x="0px" y="0px" width="1452px" height="860px"></image><foreignObject x="383px" y="165px" width="682px" height="384px"><video width="100%" height="100%" controls="controls" autoplay="autoplay"><source src="./video/aaa.mp4" type="video/mp4" /></video></foreignObject></svg>
  <script type="text/javascript">
     //调整浏览器窗口大小事件 
    window.onresize = function(){
        _autoZoom();
    }
    _autoZoom();
    function _autoZoom(){
         var svg = document.getElementById("main");
        if (svg) {
            svg.setAttribute("preserveAspectRatio", "xMinYMin meet");
            svg.setAttribute("viewBox", "0 0 1452 860");
            svg.style.overflow = "hidden";
            var viewBoxVal = svg.getAttribute("viewBox");
            if (viewBoxVal) {
                var viewBoxWidth = viewBoxVal.split(" ")[2];
                var viewBoxHeight = viewBoxVal.split(" ")[3];
                svg.removeAttribute("width");
                svg.removeAttribute("height");

                var setWidth = document.body.clientWidth;
                var setHeight = setWidth * viewBoxHeight / viewBoxWidth;
                svg.setAttribute("width", setWidth);
                svg.setAttribute("height", setHeight);
            }
        }
    }
</script>
</body>
</html>

相关推荐