繁体   English   中英

如何通过链接使元素出现在屏幕中央?

[英]How do I make an element appear in the center of a screen from a link?

我不太确定该如何表达,因此请耐心等待。

我在页面上有一张地图,上面有很多符号。 每个符号都用CSS封装在<div>标记内,以支持将该符号放置在地图上的位置。

我有一个简单的搜索页面,该页面根据<div>标记的id链接到所有这些符号。

<div class="poi" id="poi1">
    <img src="poi1.jpg" />
</div>

我知道要转到该元素,我只需要链接像http://localhost/map#poi1

到目前为止,我知道单击或手动输入此类URL时,该元素通常会显示在右上角或其他位置。

我想知道的是,是否可以通过单击超链接或手动输入URL来使该元素出现在屏幕中央?

我并没有试图使该符号看起来像是浮动在屏幕的中央。 我正在尝试做的是使其变得好像用户已滚动到地图的该部分以查看符号,从而使其位于屏幕中心附近。

我忘了提到ID是每页数百个,并且是动态生成的。

这可以用javascript完成。 这是一个例子。 我在JS代码段中添加了注释。

 // Add a method to get the position of the element from the top of the page. Element.prototype.documentOffsetTop = function () { return this.offsetTop + ( this.offsetParent ? this.offsetParent.documentOffsetTop() : 0 ); }; var element = document.getElementById('para'); // Add an event listener for click on the libk document.querySelector('.link').addEventListener('click', function(e) { // variable top = (position of element from top) - (half the height of window). This bit makes it so that the element appears in the center. var top = document.getElementById('para').documentOffsetTop() - (window.innerHeight / 2); // Remember that the above code makes it so that the top of the element is in center of the document. If you want the center of the element to be in the center, do this: // var top = element.documentOffsetTop() - (window.innerHeight / 2) + (element.clientHeight / 2); // prevent the default action of the libk e.preventDefault(); // Simply scroll to the position on click. window.scrollTo(0, top); }) 
 * { margin: 0; padding: 0; } .some, .some2 { height: 500px; border: 1px solid black; width: 500px; margin-bottom: 100px; } 
 <div class="some">some text <a href="#para" class="link">Go to para</a> </div> <div class="some2"> <p id="para">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Eveniet mollitia totam molestiae, enim corrupti facere aliquam odio cumque laborum ipsa, dolores voluptates quaerat, soluta provident itaque doloremque consequatur ratione? Fugit.</p> </div> 

编辑:这是对不同页面执行相同任务的方法。 我尝试使用纯JS解决方案,但由于某种原因window.scrollTo不会在页面加载时触发。 因此,我正在使用jQuery。

显然,此代码需要同时包含在两个页面中。 或者,您可以在目标页面中包括检查部分,然后在源页面中单击功能。

$(document).ready(function () {

    // Check if the # exists in the url
    if(window.location.hash) {

        // Get the position like in the javascript snippet above
        var scrollPoint = $(window.location.hash).offset().top - 
        (window.innerHeight / 2);

        // jump to that element
        $(window).scrollTop(scrollPoint);
    }

    $('.link').click(function (e) {

        e.preventDefault();

        // Redirect to the link
        window.location.href = this.attr('href');
    }); 
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM