如何在鼠标悬停在 google 地图标记上时滚动 window

How to scroll window on mouse over on google map marker

我试图在鼠标悬停在 google 地图标记上时滚动或滚动到特定的 div。我在第一步失败了。

这是我正在使用的代码的初始形状 alert 正在运行,但 window 没有滚动。

marker.addListener('mouseover', function() {
    window.scrollTo(0,0);
    //alert(id);
});

marker.addListener('mouseover', function() {
    $('html, body').animate({
        scrollTop: $('html, body').offset().top
    }, 2000);
})

;

我的问题是为什么它不滚动?

没有错误,但代码不工作。

尝试 this working jsbin 查看您要实现的目标的工作示例。首先向下滚动页面,你会看到一张地图;将鼠标悬停在标记上,window 将滚动回页面顶部。下面的代码。

<!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <style>
        html,
        body {
            height: 1600px;
        }

        body {
            position: relative;
        }

        #map-wrapper {
            width: 100%;
            position: absolute;
            bottom: 0;
        }

        #map {
            height: 400px;
        }
    </style>
</head>

<body>
    <h2>This is the top of the page</h2>
    <h3> Scroll down the page to see a Google map <i style="font-size:24px;" class="fa">&#xf063;</i></h3>

    <div id="map-wrapper">
        <h3>This is the map placed at the bottom of the page</h3>
        <h3>Mouse over the marker to go back to the top</h3>
        <div id="map"></div>
    </div>

    <script>
        function initMap() {
            var uluru = { lat: -25.344, lng: 131.036 };
            var map = new google.maps.Map(
                document.getElementById('map'), { zoom: 4, center: uluru });
            var marker = new google.maps.Marker({ position: uluru, map: map });

            marker.addListener('mouseover', function() {
                $('html, body').animate({
                    scrollTop: $('html, body').offset().top
                }, 1000);
                // You can use window.scrollTo(0, 0) instead if you prefer
                // window.scrollTo(0, 0);
            })
        }
    </script>

    <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
    <script src="https://maps.googleapis.com/maps/api/js?key=&libraries=places&callback=initMap" async defer></script>
</body>

</html>

希望这能帮助您指明正确的方向!