简体   繁体   中英

Determine if element has scrolled into view

I am trying to determine if an element is visible in the viewport when the user scrolls. This code works outside of a Modal, but not inside the Modal. I imagine it has something to do with the z-index , but no matter what I try it does not work. Any ideas?

app.component.ts

在此处输入图像描述

app.component.html

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Modal Example</h2>
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">
    
      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <h1>Is div shown? {{isTestDivScrolledIntoView ? 'Yes!' : 'No :-('}}</h1>


          <div #testDiv class="test">Test</div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>
      
    </div>
  </div>
  
</div>

</body>
</html>

app.component.css

    p {
    font-family: Lato;
  }
  
  h1 {
    position: fixed;
    top: 0;
    padding-bottom: 5%;
  }
  
  .test {
    text-align: center;
    height: 40px;
    margin-bottom: 40vh;
    margin-top: 40vh;
    border: 1px solid #000000;
  }

Check a feature called Intersection observer. It lets you listen for an element when it comes into view and then fire a callback.

https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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