Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

javascript - 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

enter image description here

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;
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...