百度地图JS API不能使用position:fixed

用于放置百度地图的dom元素及其任何一级父元素设置position:fixed属性时,js会报如下错误:

Uncaught TypeError: Cannot read property 'offsetLeft' of null

解决办法:对地图使用position:absolut模拟fixed样式。

若要实现地图背景固定,前面列表滚动的样式,对前面列表使用overfollw-y:scroll。对其设置下面样式可以隐藏滚动条:

::-webkit-scrollbar {
    width: 0;
    background-color: transparent;
}

demo:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <title>地图不能fixed</title>
    <script type="text/javascript"
            src="http://api.map.baidu.com/api?v=2.0&ak=你的密钥"></script>
    <style>
        .map-container {
            position: absolute;
            left: 0px;
            top: 0px;
            width: 100%;
            height: 100%;
        }

        #map {
            width: 100%;
            height: 100%;
        }

        .list-container {
            position: absolute;
            left: 0px;
            top: 0px;
            width: 100%;
            height: 100%;
            overflow-y: scroll;
        }

        .list-map {
            width: 100%;
            height: 300px;
        }

        .list {
            width: 100%;
            height: 1300px;
            background-color: yellow;
        }

        /*隐藏滚动条样式*/
        ::-webkit-scrollbar {
            width: 0;
            background-color: transparent;
        }

    </style>
</head>
<body>
<div class="map-container">
    <div id="map"></div>
</div>
<div class="list-container">
    <div class="list-map"></div>
    <div class="list">哈哈哈</div>
</div>

<script>
    // 创建Map实例
    var map = new BMap.Map("map");
    // 初始化地图,设置中心点坐标和地图级别
    map.centerAndZoom(new BMap.Point(116.404, 39.915), 11);
</script>
</body>
</html>

       

posted @ 2017-02-20 15:45  瑞way  阅读(1530)  评论(0编辑  收藏  举报