检测div是否在屏幕的特定位置

时间:2018-07-16 00:39:45

标签: javascript jquery html css

在正在运行的网站上,我希望用户滚动并单击图标以“打开”它们。例如,如果用户单击“关于我们”图标,则会有一段信息可以在其中滚动并下文字以及后退按钮。后退按钮会将用户带回到该图标,他们可以再次滚动以选择另一个图标。我想知道如何在屏幕上显示下划线图标时(而不是单击它时)对其进行检测?我在动画中使用插槽JS,但我不知道如何检测它是否在屏幕上。

我已经尝试过:

function isOnScreen(){
  console.log($("#theMiddle").height());
  if (($("#middleID").offset().top + $("#middleID").height()) >=     $("#theMiddle").height()) {
    return true;
  }
  else{
    return false;
  }
}

document.body.style.overflow = "hidden";
//the key strokes for the up and down keys
// Set up our container
var el = document.querySelector("#theMiddle");
// Create new SlotMachine
var slot = new SlotMachine(el, {});

function isOnScreen(){
  console.log($("#theMiddle").height());
  if (($("#middleID").offset().top + $("#middleID").height()) >= $("#theMiddle").height()) {
    return true;
  }
  else{
    return false;
  }
}

function open() {
    anime({
        targets: "div.right",
        translateX: {
            value: 200,
            duration: 500
        }
    });
    anime({
        targets: "div.left",
        translateX: {
            value: -200,
            duration: 500
        }
    });
}



document.onkeydown = checkKey;
function checkKey(e) {
    e = e || window.event;
    if (e.keyCode == "40") {
        //this is down
        //this will open it up
        open();
        console.log(isOnScreen());
        slot.prev();
    } else if (e.keyCode == "38") {
        open();
        console.log(isOnScreen());
        slot.next();
    }

}

//Scroll detection occurs here, without the scrollbar
$("html").on("mousewheel", function(e) {
    open();
    var delta = e.originalEvent.wheelDelta;
    if (delta < 0) {
        //This is for the scrolling down
        // animation opens up the brakets
        slot.prev();
    }
    if (delta > 0) {
        slot.next();
    }
});


//this is for detecting clicks  for the divs in the middle div
// 1 = the 2nd image , 2 = the  3rd image
$(".middle div").click(function() {
    if ($(this).index() == '1') {
        $('#theMiddle').fadeOut("slow", function() {
            $('#aboutTextID').fadeIn("slow", function() {});
            $("#backButtonID").fadeIn("slow", function() {});
            //Define the event handler here after the btn has been created
            $("#backButtonID").click(function() {
                console.log("back");
                $('#aboutTextID').fadeOut("slow", function() {
                    $("#backButtonID").fadeOut("slow", function() {
                        $('#theMiddle').fadeIn("slow", function() {});
                    });
                });
            });
        });
    }
    if ($(this).index() == '2') {
        $('#theMiddle').fadeOut("slow", function() {
            $('#applyButtonID').fadeIn("slow", function() {});
            $("#backButtonID").fadeIn("slow", function() {});
            //Define the event handler here after the btn has been created
            $("#backButtonID").click(function() {
                console.log("back");
                $('#applyButtonID').fadeOut("slow", function() {
                    $("#backButtonID").fadeOut("slow", function() {
                        $('#theMiddle').fadeIn("slow", function() {});
                    });
                });
            });
        });
    }
});
.box{
  position: relative;
  width: 100px;
  height: 100px;
  margin: 4px;
  display: inline-block;

}

div.left {
  position: absolute;
  left: 390px;
}

div.middle {
  position: absolute;
  left: 490px;
  top: 150px;
}

div.right {
  position: absolute;
  left: 870px;
}

#left,#right{
  width: 290px;
  float: left;
}

#middle{
  width: auto;
  float: left;
}
#theMiddle{
  left: 490px;
  top: 150px;
}
#foo {
  position: absolute;
  height: 300px;
  width: 400px;
  left: 490px;
  top: 100px;
  overflow-y: scroll
}

#aboutTextID{
  position: absolute;
  display: none;
  height: 300px;
  width: 400px;
  left: 490px;
  top: 100px;
  overflow-y: scroll
}

.backButton{
  position: absolute;
  display: none;
  height: 20px;
  width: 70px;
  left: 490px;
  top: 90px;
}
#applyButtonID{
  position: absolute;
  display: none;
  height: 20px;
  width: 120px;
  left: 600px;
  top:200px;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Underscores</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
  <button type="button" name="Back" class="backButton" id="backButtonID">Back</button>


  <div id= "left" class="left">
    <img src="https://s3.amazonaws.com/underscores.xyz/images/left.png" alt="">
  </div>

  <p id='aboutTextID' >"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
  </p>

<a id="applyButtonID" class="typeform-share button" href="https://bhagyeshpatel1.typeform.com/to/ytfEgw" data-mode="popup" style="text-decoration:none;background-color:#662c92;color:white;cursor:pointer;font-family:Helvetica,Arial,sans-serif;font-size:20px;line-height:50px;text-align:center;margin:0;height:50px;padding:0px 33px;border-radius:25px;max-width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-weight:bold;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;" \
target="_blank">Launch me </a>
<script> (function() {
  var qs,js,q,s,d=document, gi=d.getElementById, ce=d.createElement, gt=d.getElementsByTagName, id="typef_orm_share", b="https://embed.typeform.com/";
    if(!gi.call(d,id)){
      js=ce.call(d,"script");
      js.id=id;
      js.src=b+"embed.js";
      q=gt.call(d,"script")[0];
      q.parentNode.insertBefore(js,q) }
    })()
</script>
  <div class="middle" id = "theMiddle" style="width: 400px; height: 300px">
    <div><img src="https://s3.amazonaws.com/underscores.xyz/selectionIcon/About.png" alt="" class="icons" id="aboutID"></div>
    <div><img src="https://s3.amazonaws.com/underscores.xyz/selectionIcon/job.png" alt="" class="icons" id="jobID"></div>
    <div><img src="https://s3.amazonaws.com/underscores.xyz/selectionIcon/middle.png" alt="" class="icons" id="middleID"></div>
  </div>

  <div id= "right" class="right"><img src="https://s3.amazonaws.com/underscores.xyz/images/right.png" alt=""></div>

  <script src="https://cdn.jsdelivr.net/npm/jquery-slotmachine@4.0.0/dist/slotmachine.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.2.0/anime.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  <script src="back.js" charset="utf-8"></script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

要获取元素的位置,可以使用getBoundingClientRect()

示例:

var div = document.getElementById("example");
var left = div.getBoundingClientRect().left;
var top = div.getBoundingClientRect().top;
alert("X position: " + left + ", Y position: " + top);