javascript与CSS复习(《精通javascript》)(2)


//a function for setting the horizontal position of an element
function setX(elem, pos) {
  //set the 'left' css property, using pixel units
  elem.style.left = pos + 'px';
}
//a function for setting the vertical position of an element
function setY(elem, pos) {
  //set the 'top' css property, using pixel units
  elem.style.top = pos + 'px';
}


再来两个函数,用于调准元素的当前位置,在动画效果中很实用

复制代码 代码如下:


//a function for adding a number of pixels to the horizontal
//position of an element
function addX(elem, pos) {
  //get the current horz. position and add the offset to it
setX(elem, posX(elem) + pos);
}
//a function that can be used to add a number of pixels to the
//vertical position of an element
function addY(elem, pos) {
  //get the current vertical position and add the offset to it
setY(elem, posY(elem) + pos);
}


知道如何获取元素位置之后,我们再来看看如何获取元素的尺寸,
获取元素当前的高度和宽度

复制代码 代码如下:


function getHeight(elem) {
  return parseInt(getStyle(elem, 'height'));
}
function getWidth(elem) {
  return parseInt(getStyle(elem, 'width'));
}


大多数情况下,以上的方法够用了,但是在一些动画交互中会出现问题。比如以0像素开始的动画,你需要事先知道元素究竟能有多高或多宽,其二当元素的display属性为none时,你会得不到值。这两个问题都会在执行动画的时候发生。为此作者给出了获得元素潜在高度和宽度的函数。

复制代码 代码如下:


//查找元素完整的、可能的高度
function fullHeight(elem) {
  //如果元素是显示的,那么使用offsetHeight就能得到高度,如果没有offsetHeight,则使用getHeight()
  if(getStyle(elem, 'display') != 'none')
      return elem.offsetHeight || getHeight(elem);
//否则,我们必须处理display为none的元素,所以重置它的css属性以获得更精确的读数
var old = resetCSS(elem, {
  display:'',
visibility:'hidden',
position:'absolute'
});
//使用clientHeigh找出元素的完整高度,如果还不生效,则使用getHeight函数
var h = elem.clientHeight || getHeight(elem);
//最后,恢复其css的原有属性
restoreCSS(elem, old);
//并返回元素的完整高度
return h;
}
//查找元素完整的、可能的宽度
function fullWidth(elem) {
  //如果元素是显示的,那么使用offsetWidth就能得到宽度,如果没有offsetWidth,则使用getWidth()
if(getStyle(elem, 'display') != 'none')
    return elem.offsetWidth || getWidth(elem);
//否则,我们必须处理display为none的元素,所以重置它的css以获取更精确的读数
var old = resetCSS(elem, {
   display:'',
visibility:'hidden',
position:'absolute'
});
//使用clientWidth找出元素的完整高度,如果还不生效,则使用getWidth函数
var w = elem.clientWidth || getWidth(elem);
//最后,恢复原有CSS
 restoreCSS(elem, old);
//返回元素的完整宽度
return w;
}
//设置一组CSS属性的函数
function resetCSS(elem, prop) {
  var old = {};
//遍历每个属性
for(var i in prop) {
  //记录旧的属性值
old[i] = elem.style[i];
    //设置新的值
    elem.style[i] = prop[i];
}
return old;
}
//恢复原有CSS属性
function restoreCSS(elem, prop) {
  for(var i in prop)
    elem.style[i] = prop[i];
}


还有不少内容,明天继续,写写效率低下了,笔记本屏幕太小,开个pdf,写着文章老来回切换,真是。。。是时候弄个双显了!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wdxfdx.html