javascript與CSS復習(《精通javascript》)
2024-09-06 12:45:33
供稿:網友
如:elem.style.height 或者 elem.style.height = '100px', 這里要注意的是設置任何幾何屬性必須明確尺寸單位(如px),同時任何幾何屬性返回的是表示樣式的字符串而非數值(如'100px'而非100)。另外像elem.style.height這樣的操作,也能獲取元素style屬性中設置的樣式值,如果你把樣式統一放在css文件中,上述方法只會返回一個空串。為了獲取元素真實、最終的樣式,書中給出了一個函數
代碼如下:
//get a style property (name) of a specific element (elem)
function getStyle(elem, name) {
// if the property exists in style[], then it's been set
//recently (and is current)
if(elem.style[name]) return elem.style[name];
//otherwise, try to use IE's method
else if (elem.currentStyle) return elem.currentStyle[name];
//Or the W3C's method, if it exists
else if (document.defaultView && document.defaultView.getComputedStyle) {
//it uses the traditional 'text-align' style of rule writing
//instead of textAlign
name = name.replace(/[A-Z]/g, '-$1');
name = name.toLowerCase();
//get the style object and get the value of the property ( if it exists)
var s = document.defaultView.getComputedStyle(elem,'');
return s && s.getPropertyValue(name);
} else return null;
}
理解如何獲取元素的在頁面的位置是構造交互效果的關鍵。先復習下css中position屬性值的特點。
static:靜態定位,這是元素定位的默認方式,它簡單的遵循文檔流。但元素靜態定位時,top和left屬性無效。
relative:相對定位,元素會繼續遵循文檔流,除非受到其他指令的影響。top和left屬性的設置會引起元素相對于它的原始位置進行偏移。
absolute:絕對定位,絕對定位的元素完全擺脫文檔流,它會相對于它的第一個非靜態定位的祖先元素而展示,如果沒有這樣的祖先元素,它的定位將相對于整個文檔。
fixed:固定定位把元素相對于瀏覽器窗口而定位。它完全忽略瀏覽器滾動條的拖動。
作者封裝了一個跨瀏覽器的獲取元素頁面位置的函數
其中有幾個重要元素的屬性:offsetParent,offsetLeft,offsetTop(可直接點擊到Mozilla Developer Center的相關頁面)
代碼如下:
//find the x (horizontal, Left) position of an element
function pageX(elem) {
//see if we're at the root element, or not
return elem.offsetParent ?
//if we can still go up, add the current offset and recurse upwards
elem.offsetLeft + pageX(elem.offsetParent) :
//otherwise, just get the current offset
elem.offsetLeft;
}
//find the y (vertical, top) position of an element
function pageY(elem) {
//see if we're at the root element, or not
return elem.offsetParent ?
//if we can still go up, add the current offset and recurse upwards