日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

jQuery offset( ) 方法

發布時間:2024/3/24 编程问答 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 jQuery offset( ) 方法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

通過jQuery 的offset( )方法,我們可以設置或者獲取被選元素相對于文檔的位置。需要注意的是,當我們獲取被選元素的位置時,只會返回匹配到的第一個元素的位置。當我們設置被選元素的位置時,將會設置所有匹配到的元素的位置。

注意:該方法返回的是一個包含left和top屬性的對象。

(1)獲取位置

語法格式:

$(selector).offset()

(2)設置位置

語法格式:

常規方式

$(selector).offset({top:value,left:value})

函數方式

$(selector).offset(function(n,current))

其中,n為匹配到的元素的索引,current為元素的當前位置

示例:

1.獲取位置

(1)兩個DIV元素,只返回第一個匹配到的DIV的位置:

<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Document</title><script src="../jQuery/jQuery.js"></script><script>$(document).ready(function(){var position = $("div").offset();console.log(position);})</script><style>.one {position: absolute;left: 100px;top: 100px;width: 100px;height: 100px;background-color: rgba(38, 172, 26, 0.644);}.two {position: absolute;left: 200px;top: 200px;width: 100px;height: 100px;background-color: rgba(53, 26, 172, 0.644);}</style> </head> <body><div class="one"></div><div class="two"></div> </body> </html>

控制臺輸出:

2.設置位置

(1)常規方式

<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Document</title><script src="../jQuery/jQuery.js"></script><script>$(document).ready(function(){$("button").click(function(){$(".para").offset({left:100,top:100})})})</script><style>.para {position: absolute;left: 50px;top: 50px;background-color: rgba(38, 172, 26, 0.644);}</style> </head> <body><button>按鈕</button><p class="para">我是一個段落。</p> </body> </html>

?

點擊按鈕,P元素的位置將會發生改變:

(2)函數方式

<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Document</title><script src="../jQuery/jQuery.js"></script><script>$(document).ready(function(){$("button").click(function(){$("div").offset(function(n,current){var newPosition = new Object();newPosition.left = current.left + 200;newPosition.top = current.top + 200;return newPosition;})})})</script><style>.one {position: absolute;left: 50px;top: 50px;width: 100px;height: 100px;background-color: rgba(38, 172, 26, 0.644);}.two {position: absolute;left: 100px;top: 100px;width: 100px;height: 100px;background-color: rgba(53, 26, 172, 0.644);}</style> </head> <body><button>按鈕</button><div class="one"></div><div class="two"></div> </body> </html>

點擊按鈕,兩個DIV的位置都會被改變:

總結

以上是生活随笔為你收集整理的jQuery offset( ) 方法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。