หลังจากพยายามหาวิธีแก้ปัญหาที่จัดการทุกสถานการณ์ (ตัวเลือกสำหรับการเคลื่อนไหวการเลื่อนการเติมรอบวัตถุเมื่อมันเลื่อนเข้ามาดูการทำงานแม้ในสถานการณ์ที่คลุมเครือเช่นใน iframe) ในที่สุดฉันก็เลยเขียนโซลูชันของตัวเองขึ้นมา เนื่องจากดูเหมือนว่าจะใช้งานได้เมื่อโซลูชันอื่น ๆ ล้มเหลวฉันจึงคิดว่าจะแบ่งปัน:
function scrollIntoViewIfNeeded($target, options) {
var options = options ? options : {},
$win = $($target[0].ownerDocument.defaultView), //get the window object of the $target, don't use "window" because the element could possibly be in a different iframe than the one calling the function
$container = options.$container ? options.$container : $win,
padding = options.padding ? options.padding : 20,
elemTop = $target.offset().top,
elemHeight = $target.outerHeight(),
containerTop = $container.scrollTop(),
//Everything past this point is used only to get the container's visible height, which is needed to do this accurately
containerHeight = $container.outerHeight(),
winTop = $win.scrollTop(),
winBot = winTop + $win.height(),
containerVisibleTop = containerTop < winTop ? winTop : containerTop,
containerVisibleBottom = containerTop + containerHeight > winBot ? winBot : containerTop + containerHeight,
containerVisibleHeight = containerVisibleBottom - containerVisibleTop;
if (elemTop < containerTop) {
//scroll up
if (options.instant) {
$container.scrollTop(elemTop - padding);
} else {
$container.animate({scrollTop: elemTop - padding}, options.animationOptions);
}
} else if (elemTop + elemHeight > containerTop + containerVisibleHeight) {
//scroll down
if (options.instant) {
$container.scrollTop(elemTop + elemHeight - containerVisibleHeight + padding);
} else {
$container.animate({scrollTop: elemTop + elemHeight - containerVisibleHeight + padding}, options.animationOptions);
}
}
}
$target
เป็นวัตถุ jQuery ที่มีวัตถุที่คุณต้องการเลื่อนดูถ้าจำเป็น
options
(เป็นทางเลือก) สามารถมีตัวเลือกต่อไปนี้ผ่านในวัตถุ:
options.$container
- วัตถุ jQuery ที่ชี้ไปยังองค์ประกอบที่มี $ target (กล่าวอีกนัยหนึ่งคือองค์ประกอบใน Dom ด้วยแถบเลื่อน) เริ่มต้นไปที่หน้าต่างที่มีองค์ประกอบ $ target และฉลาดพอที่จะเลือกหน้าต่าง iframe อย่าลืมใส่ $ ในชื่อคุณสมบัติ
options.padding
- ช่องว่างภายในเป็นพิกเซลเพื่อเพิ่มด้านบนหรือด้านล่างของวัตถุเมื่อเลื่อนลงในมุมมอง ด้วยวิธีนี้มันไม่ถูกต้องกับขอบของหน้าต่าง ค่าเริ่มต้นถึง 20
options.instant
- หากตั้งค่าเป็นจริงจะไม่ใช้ jQuery animate และการเลื่อนจะปรากฏขึ้นในตำแหน่งที่ถูกต้องทันที ค่าเริ่มต้นเป็นเท็จ
options.animationOptions
- ตัวเลือก jQuery ใด ๆ ที่คุณต้องการส่งต่อไปยังฟังก์ชัน jQuery animate (ดูที่http://api.jquery.com/animate/ ) ด้วยสิ่งนี้คุณสามารถเปลี่ยนระยะเวลาของภาพเคลื่อนไหวหรือมีฟังก์ชั่นการโทรกลับเมื่อดำเนินการเลื่อนเสร็จสมบูรณ์ ใช้งานได้options.instant
ก็ต่อเมื่อตั้งค่าเป็นเท็จ หากคุณต้องการที่จะมีการเคลื่อนไหวทันที แต่มีการเรียกกลับตั้งแทนการใช้options.animationOptions.duration = 0
options.instant = true