[英]JQuery to Javascript function Scroll
我有JQuery代码,有人可以告诉我如何用JavaScript编写代码吗? 我有一个不使用JQuery的项目。
也许是一个愚蠢的问题,但我无能为力
$(document).ready(function() {
var boxMargin = 15;
var boxLeft = $("#box").position().left;
var containerHeight = $("#box").closest("#content").height();
var containerOffset = $("#box").closest("#content").offset().top;
var height = $("#box").outerHeight();
$(window).scroll(function() {
$("#box").each(function() {
var windowScroll = $(window).scrollTop();
if (windowScroll < containerOffset) {
$(this).removeClass("fixed bottom");
} else if (windowScroll > containerHeight + containerOffset - height - 2*boxMargin) {
$(this).removeClass("fixed").addClass("bottom").css({"left": ""});
} else {
var leftValue = boxLeft + $(this).closest("#content").offset().left;
$(this).removeClass("bottom").addClass("fixed").css({"left": leftValue});
}
});
});
});
这是我的尝试:
function offTop(elem){
/*from https://www.quirksmode.org/js/findpos.html, I added some handy stuff to the return statement*/
var curleft = curtop = 0;
if(obj.offsetParent){
do{
curleft+=obj.offsetLeft;
curtop+=obj.offsetTop;
}while(obj=obj.offsetParent);
return {"top": curtop, "left": curleft};
}
}
window.attachEvent("onload", function(){
var boxMargin = 15;
var boxLeft = document.querySelector("#box").scrollLeft;
var containerHeight = document.querySelector("#content").scrollHeight;
var containerOffset = offTop( document.querySelector("#content") ).top;
var height = document.querySelector("#box").offsetHeight;
window.addEventListener("scroll",function(){
for(var el of document.querySelectorAll("#box")){
var windowScroll = window.pageYOffset;/*maybe sthng better here ?*/
if(windowScroll < containerOffset){
el.classList.remove("fixed");
el.classList.remove("bottom");
}else if(windowScroll > containerHeight+containerOffset-height-(2*boxMargin)){
el.classList.remove("fixed");
el.classList.add("bottom");
el.style.left=undefined;/*i dunno if empty string is enough here, so i put undefined instead*/
}else{
var leftValue = boxLeft + offTop( document.querySelector("#content") ).left;
el.classList.remove("bottom");
el.classList.add("fixed");
el.style.left = ""+leftValue+"px";
}
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.