사용자가 특정 요소로 스크롤할 때 이벤트 트리거 - jQuery 사용
나는 한 페이지 아래에 있는 h1을 가지고 있습니다.
<h1 id="scroll-to">TRIGGER EVENT WHEN SCROLLED TO.</h1>
사용자가 h1로 스크롤하거나 브라우저 보기에 있을 때 경고를 트리거합니다.
$('#scroll-to').scroll(function() {
alert('you have scrolled to the h1!');
});
이거 어떻게 하는 거지?
계산할 수 있습니다.offset
요소의 그리고 나서 그것과 비교합니다.scroll
다음과 같은 값:
$(window).scroll(function() {
var hT = $('#scroll-to').offset().top,
hH = $('#scroll-to').outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
if (wS > (hT+hH-wH)){
console.log('H1 on the view!');
}
});
업데이트된 데모 피들 경보 없음 - 대신 요소 페이드인()
요소가 뷰포트 내부에 있는지 확인하기 위해 코드가 업데이트되었습니다.따라서 if 문에 몇 가지 규칙을 추가할 때 위로 스크롤하든 아래로 스크롤하든 작동합니다.
if (wS > (hT+hH-wH) && (hT > wS) && (wS+wH > hT+hH)){
//Do something
}
이 질문을 jQuery의 최상의 답변과 결합하면 사용자가 페이지의 특정 부분을 스크롤할 때 트리거 작업이 수행됩니다.
var element_position = $('#scroll-to').offset().top;
$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var scroll_pos_test = element_position;
if(y_scroll_pos > scroll_pos_test) {
//do stuff
}
});
갱신하다
요소가 맨 위가 아닌 화면의 절반 위에 있을 때 트리거되도록 코드를 개선했습니다.또한 사용자가 화면 하단을 누르고 기능이 아직 실행되지 않은 경우 코드를 트리거합니다.
var element_position = $('#scroll-to').offset().top;
var screen_height = $(window).height();
var activation_offset = 0.5;//determines how far up the the page the element needs to be before triggering the function
var activation_point = element_position - (screen_height * activation_offset);
var max_scroll_height = $('body').height() - screen_height - 5;//-5 for a little bit of buffer
//Does something when user scrolls to it OR
//Does it when user has reached the bottom of the page and hasn't triggered the function yet
$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var element_in_view = y_scroll_pos > activation_point;
var has_reached_bottom_of_page = max_scroll_height <= y_scroll_pos && !element_in_view;
if(element_in_view || has_reached_bottom_of_page) {
//Do something
}
});
이러한 기능을 수행하는 기존 라이브러리를 활용하는 것이 최선이라고 생각합니다.
http://imakewebthings.com/waypoints/
요소가 뷰포트의 맨 위에 도달할 때 꺼지는 요소에 수신기를 추가할 수 있습니다.
$('#scroll-to').waypoint(function() {
alert('you have scrolled to the h1!');
});
사용 중인 놀라운 데모:
http://tympanus.net/codrops/2013/07/16/on-scroll-header-effects/
View 라이브러리는 이벤트를 트리거했으며 jquery 1.8 이상에서 잘 작동합니다! https://github.com/protonet/jquery.inview
$('div').on('inview', function (event, visible) {
if (visible == true) {
// element is now visible in the viewport
} else {
// element has gone out of viewport
}
});
이 페이지를 읽어 보십시오. https://remysharp.com/2009/01/26/element-in-view-event-plugin
성공적인 스크롤 후 한 번만 스크롤
참고: 성공적인 스크롤이란 사용자가 원하는 요소로 스크롤했을 때 또는 원하는 요소가 뷰에 있을 때를 의미합니다.
수락된 답변은 저에게 90% 효과가 있어서 실제로 한 번만 발사하기 위해 약간 수정해야 했습니다.
$(window).on('scroll',function() {
var hT = $('#comment-box-section').offset().top,
hH = $('#comment-box-section').outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
if (wS > ((hT+hH-wH)-500)){
console.log('comment box section arrived! eh');
// This detaches the scroll so doStuff() won't run more than once
$(window).off('scroll');
doStuff();
}
});
모든 장치에 사용할 수 있습니다.
$(document).on('scroll', function() {
if( $(this).scrollTop() >= $('#target_element').position().top ){
do_something();
}
});
Intersection Observer는 IMO 중 가장 좋은 것일 수 있습니다. 외부 라이브러리가 없으면 정말 잘 작동합니다.
const options = {
root: null,
threshold: 0.25, // 0 - 1 this work as a trigger.
rootMargin: '150px'
};
const target = document.querySelector('h1#scroll-to');
const observer = new IntersectionObserver(
entries => { // each entry checks if the element is the view or not and if yes trigger the function accordingly
entries.forEach(() => {
alert('you have scrolled to the h1!')
});
}, options);
observer.observe(target);
jQuery 플러그인을 사용할 수 있습니다.inview
이와 같은 사건:
jQuery('.your-class-here').one('inview', function (event, visible) {
if (visible == true) {
//Enjoy !
}
});
링크: https://remysharp.com/2009/01/26/element-in-view-event-plugin
이것이 당신이 필요로 하는 것이어야 합니다.
Javascript:
$(window).scroll(function() {
var hT = $('#circle').offset().top,
hH = $('#circle').outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
console.log((hT - wH), wS);
if (wS > (hT + hH - wH)) {
$('.count').each(function() {
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 900,
easing: 'swing',
step: function(now) {
$(this).text(Math.ceil(now));
}
});
}); {
$('.count').removeClass('count').addClass('counted');
};
}
});
CSS:
#circle
{
width: 100px;
height: 100px;
background: blue;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
border-radius: 50px;
float:left;
margin:5px;
}
.count, .counted
{
line-height: 100px;
color:white;
margin-left:30px;
font-size:25px;
}
#talkbubble {
width: 120px;
height: 80px;
background: green;
position: relative;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
float:left;
margin:20px;
}
#talkbubble:before {
content:"";
position: absolute;
right: 100%;
top: 15px;
width: 0;
height: 0;
border-top: 13px solid transparent;
border-right: 20px solid green;
border-bottom: 13px solid transparent;
}
HTML:
<div id="talkbubble"><span class="count">145</span></div>
<div style="clear:both"></div>
<div id="talkbubble"><span class="count">145</span></div>
<div style="clear:both"></div>
<div id="circle"><span class="count">1234</span></div>
다음 부트 공급을 확인하십시오. http://www.bootply.com/atin_agarwal2/cJBywxX5Qp
만약 당신이 자바스크립트 버전을 찾고 있다면요.스크롤 이벤트 수신기에서 이 메서드를 호출할 수 있습니다.
showScrollTop = () =>{
const currentScrollPosition = window.pageYOffset;
let elementID = 'service-selector'
const elementOffsetTop = document.getElementById(elementID).offsetTop
if ( currentScrollPosition > elementOffsetTop){
// place your logic here
} else {
// place your logic here
}
}
window.addEventListener('scroll', showScrollTop)
스크롤 위치를 기반으로 많은 기능을 수행하는 경우 Scroll magic(http://scrollmagic.io/) 은 전적으로 이러한 목적을 위해 구축되었습니다.
사용자가 스크롤할 때 특정 요소에 도달할 때를 기준으로 JS를 쉽게 트리거할 수 있습니다.또한 GSAP 애니메이션 엔진(https://greensock.com/) 과 통합되어 시차 스크롤 웹사이트에 적합합니다.
DaniP의 답변을 간단히 수정하면 장치 뷰포트의 범위를 벗어날 수 있는 요소를 다루는 모든 사용자를 위한 것입니다.
약간의 조건부만 추가됨 - 뷰포트보다 큰 요소의 경우 위쪽 절반이 뷰포트를 완전히 채우면 요소가 나타납니다.
function elementInView(el) {
// The vertical distance between the top of the page and the top of the element.
var elementOffset = $(el).offset().top;
// The height of the element, including padding and borders.
var elementOuterHeight = $(el).outerHeight();
// Height of the window without margins, padding, borders.
var windowHeight = $(window).height();
// The vertical distance between the top of the page and the top of the viewport.
var scrollOffset = $(this).scrollTop();
if (elementOuterHeight < windowHeight) {
// Element is smaller than viewport.
if (scrollOffset > (elementOffset + elementOuterHeight - windowHeight)) {
// Element is completely inside viewport, reveal the element!
return true;
}
} else {
// Element is larger than the viewport, handle visibility differently.
// Consider it visible as soon as it's top half has filled the viewport.
if (scrollOffset > elementOffset) {
// The top of the viewport has touched the top of the element, reveal the element!
return true;
}
}
return false;
}
저는 항상 같은 코드를 사용하기 때문에 간단한 jquery 플러그인을 추가했습니다. 길이 480바이트, 속도가 빠릅니다.바인딩된 요소만 런타임에 분석됩니다.
https://www.npmjs.com/package/jquery-on-scrolled-to
그럴 것이다. $('#scroll-to').onScrolledTo(0, function() { alert('you have scrolled to the h1!'); });
또는 h1의 절반이 표시되었을 때 경고해야 할 경우 0 대신 0.5를 사용합니다.
신속하고 빠른 구현,
let triggered = false;
$(window).on('scroll',function() {
if (window.scrollY > ($('#scrollTo').offset().top+$('#scrollTo').outerHeight()-window.innerHeight) & !triggered){
console.log('triggered here on scroll..');
triggered = true;
}
});
변수 triggered = false
한 번만 발생하게 합니다. 그렇지 않으면 요소를 통과할 때마다 이 작업이 트리거됩니다.
언급URL : https://stackoverflow.com/questions/21561480/trigger-event-when-user-scroll-to-specific-element-with-jquery
'programing' 카테고리의 다른 글
asp에서 선택한 값 읽기:jQuery를 사용한 라디오 버튼 목록 (0) | 2023.08.12 |
---|---|
jQuery 'if .change() 또는 .keyup()' (0) | 2023.08.12 |
Oracle의 sqlnet.log 파일 생성 중지 (0) | 2023.08.07 |
iPad용 Safari에서 jQuery를 사용하여 터치 이벤트를 인식하려면 어떻게 해야 합니까?가능합니까? (0) | 2023.08.07 |
Info.plist에서 버전 읽기 (0) | 2023.08.07 |