最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to keep element in viewport? - Stack Overflow

programmeradmin3浏览0评论

I have a html element which is displayed when a button is clicked. It‘s kinda like a popup. I want to check if it’s in the ViewPort of the browser and then place it inside the ViewPort . Is there a right way to achieve that?

At the moment I’m checking the height of the ViewPort and pare it to the point where the element will be attached to. So I do something like this:

If(window.innerHeight > yPointWhereElementIsAttachedTo + heightOfElement) //attach element; 

But what is the right way to do it?

I have a html element which is displayed when a button is clicked. It‘s kinda like a popup. I want to check if it’s in the ViewPort of the browser and then place it inside the ViewPort . Is there a right way to achieve that?

At the moment I’m checking the height of the ViewPort and pare it to the point where the element will be attached to. So I do something like this:

If(window.innerHeight > yPointWhereElementIsAttachedTo + heightOfElement) //attach element; 

But what is the right way to do it?

Share Improve this question edited Aug 2, 2019 at 8:40 str 45.1k18 gold badges114 silver badges134 bronze badges asked Aug 2, 2019 at 8:08 AlexAlex 1832 silver badges16 bronze badges 1
  • please provide the code of your example, you say you have the html element, make a code section showing your html element. when you say you "do something like this" please show you do that something like this – user254694 Commented Aug 2, 2019 at 8:14
Add a ment  | 

2 Answers 2

Reset to default 3

This can be achieved by using position: fixed; on an element with positioning.

For example:

.fixed {
  position: fixed;
  width: 300px;
  height: 100px;
  background: red;
  left: 10px;
  top: 40px;
}

.wrapper {
  min-height: 4000px;
}
<div class="wrapper">
  <div class="fixed">
    I am fixed in the viewport
  </div>
</div>

You could use scrollIntoView() if a more dynamic approach is required.

 var elmnt = document.getElementById("content");
 elmnt.scrollIntoView();

https://www.w3schools./jsref/met_element_scrollintoview.asp

发布评论

评论列表(0)

  1. 暂无评论