jQuery offset( ) 方法
生活随笔
收集整理的這篇文章主要介紹了
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( ) 方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 直播过程中的掌声,口哨,背景音等音效怎么
- 下一篇: CScript 错误: 加载设置失败(拒