如何使用 jQuery 在滾動時更新滑鼠位置?
在 jQuery 中,我們可以觸發 'mousemove' 事件來檢測滑鼠指標在網頁上的位置。此外,我們可以使用 'scroll' 事件檢測滾動,並從 y 位置減去該值以獲取滑鼠的相對位置。
使用 'overflow-y: scroll' CSS 屬性,我們可以使任何 div 可滾動。
語法
使用者可以按照以下語法在 div 上滾動時獲取滑鼠的相對位置。
$('#main').scroll(function (event) {
if (finalScroll != $('#main').scrollTop()) {
location_y -= finalScroll;
finalScroll = $('#main').scrollTop();
location_y += finalScroll;
}
});
在上述語法中,我們從 y 座標減去上次滾動值,將滾動重置到頂部,並更新位置 y。
步驟
步驟 1 - 設定 div 元素上的滾動。
步驟 2 - 當用戶移動滑鼠指標時觸發 'mousemove' 事件,並使用 'e.pageX' 和 'e.pageY' 獲取滑鼠的 x 和 y 座標。並將這些值儲存在 location_x 和 location_y 變數中。
步驟 3 - 當用戶在 div 上滾動時,觸發 'scroll' 事件。
步驟 4 - 接下來,檢查 finalScroll 變數的值是否等於 scrollToTop()。如果是,則表示使用者沒有滾動。否則,我們需要獲取滑鼠的相對座標。
步驟 5 - 要獲取滑鼠座標的相對位置,請從 location_y 中減去滾動值。
步驟 6 - 之後,再次將 finalScroll 變數的值設定為頂部。
步驟 7 - 現在,再次將滾動的初始值新增到 location_x 變數中。
讓我們透過示例來理解上述步驟。例如,滾動到頂部的值為 10。現在,使用者已滾動到 30,滑鼠位置為 50。因此,我們需要從滑鼠位置減去 30,並從滑鼠位置減去 10(即初始滾動值),以獲取滑鼠的相對座標。
示例
在下面的示例中,我們建立了 div 並添加了一些內容。此外,我們還使其可滾動。使用者可以移動滑鼠以獲取滑鼠指標的位置。此外,使用者可以嘗試在滾動後獲取滑鼠位置,它將提供相對滑鼠座標,使用者可以在輸出中觀察到。
<html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js">
</script>
</head>
<body>
<h3>Updating the mouse location while scrolling on the div using jQuery</h3>
<div> Mouse Coordinates -
<span id = "location"> </span>
</div>
<div id = "main" style = "overflow-y: scroll;
height:100px;width: 500px">
<br> <br>
TutorialsPoint is a popular online learning platform that offers a vast array of tutorials and courses on
various technical and non-technical subjects. Their courses cover a wide range of topics, including programming,
web development, database management, digital marketing, and more. The platform is user-friendly, with
easy-to-follow lessons and examples that help learners grasp concepts quickly. TutorialsPoint also provides
certification courses that can enhance your career opportunities. The site is updated regularly to keep up with
the latest trends and technologies.
</div>
<br> <br>
<div> Scrolled location is -
<span id = "scroll"> </span>
</div>
<script>
var location_x = 0;
var location_y = 0;
var finalScroll = 0;
$(document).ready(function (event) {
$(document).mousemove(
(e) => {
location_x = e.pageX;
location_y = e.pageY;
$("#location").text("X coordinate is - " + location_x + ", Y coordinate is - " + location_y);
}
);
$('#main').scroll(function (event) {
if (finalScroll != $('#main')
.scrollTop()) {
location_y -= finalScroll;
finalScroll = $('#main')
.scrollTop();
location_y += finalScroll;
$("#scroll").text("Scrolled coordinate is - " + location_x + ", Y coordinate is - " + location_y);
}
});
});
</script>
</body>
</html>
使用者學習瞭如何在 JQuery 中獲取滑鼠的相對座標。使用者可以使用 'mousemove' 事件來獲取絕對座標。之後,我們可以獲取滾動值,從滑鼠座標中減去最終滾動值,並將初始滾動值新增到滑鼠座標中。
如果使用者想要獲取相對於 x 的相對座標,則應將 'scrollLeft() 方法與 x 座標一起使用。
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP