欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

js CSS操作方法集合_javascript技巧

程序员文章站 2022-05-28 13:17:29
...
//获取元素的真实的,最终的CSS样式属性值的函数
function getStyle(elem,name){
if(elem.style[name]){
return elem.style[name];
}else if(elem.currentStyle){
return elem.currentStyle[name];
}else if(document.defaultView && document.defaultView.getComputedStyle){
name = name.replace(/([A-Z])/g,"-$1");
name = name.toLowerCase();

var s = document.defaultView.getComputedStyle(elem,"");
return s && s.getPropertyValue(name);
}else{
return null;
}
}
//两个确定元素相对于整个文档的X和Y位置的辅助位置
function pageX(elem){
return elem.offsetParent?
elem.offsetLeft+pageX(elem.offsetParent):
elem.offsetLeft;
}

function pageY(elem){
return elem.offsetParent?
elem.offsetTop+pageY(elem.offsetParent):
elem.offsetTop;
}
//确定元素相对于父亲的位置的两个函数
function parentX(elem){
return elem.parentNode == elem.offsetParent?
elem.offsetLeft:
pageX(elem)-pageX(elem.parentNode);
}

function parentY(elem){
return elem.parentNode==elem.offsetParent?
elem.offsetTop:
pageY(elem)-pageY(elem.parentNode);
}
//确定元素相对于它的CSS容器的位置
function posX(elem){
return parseInt(getStyle(elem,"left"));
}
function posY(elem){
return parseInt(getStyle(elem,"top"));
}
//设置元素x和y位置(与当前位置无关)的函数
function setX(elem,pos){
elem.style.left = pos+"px";
}
function setY(elem,pos){
elem.style.top = pos+"px";
}
//调整元素相对于当前位置的距离的函数
function addX(elem,pos){
setX(posX(elem)+pos);
}
function addY(elem,pos){
setY(posY(elem)+pos);
}

//获取元素当前的高度和宽度
function getHeight(elem){
return parseInt(getStyle(elem,'height'));
}
function getWidth(elem){
return parseInt(getStyle(elem,'width'));
}
//即是元素隐藏,也能分别获取它潜在的完整高度和宽度的两个函数
function fullHeight(elem){
if(getStyle(elem,'display')!='none'){
return elem.offsetHeight||getHeight(elem);
}
var old = resetCSS(elem,{
display:'',
visibility:'hidden',
position:'absolute'
});
var h = elem.clientHeight||getHeight(elem);
restoreCSS(elem,old);
return h;
}

function fullWidth(elem){
if(getStyle(elem,'display')!='none'){
return elem.offsetWidth || getWidth(elem);
}
var old = resetCSS(elem,{
display:'',
visibility:'hidden',
position:'absolute'
});
var w = elem.clientWidth || getWidth(elem);
restoreCSS(elem,old);
return w;
}

function resetCSS(elem,prop){
var old = [];
for(var i in prop){
old[i] = elem.style[i];
elem.style[i] = prop[i];
}
return old;
}
function restoreCSS(elem,prop){
for(var i in prop){
elem.style[i] = prop[i];
}
}
//使用CSS的display属性来切换元素可见性的一组函数
function hide(elem){
var curDisplay = getStyle(elem,'display');
if(curDisplay != 'none'){
elem.$oldDisplay= curDisplay;
}
elem.style.display = 'none';
}
function show(elem){
elem.style.display = elem.$oldDisplay ||'';

}
//设置元素的透明度
function setOpacity(elem,level){
if(elem.filters){
elem.style.filters = 'alpha(opacity='+level+')';
}else{
elem.style.opacity = level/100;
}
}
相关标签: js CSS 操作