zoukankan      html  css  js  c++  java
  • html元素elem.style.top.left始终为空

    有如下元素:

    <div id="div1"   >div1</div>

    #div1{
    100px;
    height:100px;
    position:absolute;
    left:0;
    top:0;
    background: red;
    }

    js获取:

    var xpos=parseInt(elem.style.left);
    var ypos=parseInt(elem.style.top);

    得到的xpos为Nan,为什么?

    获取css 设置的style值 
    需要使用  document.defaultView..getComputedStyle(node, null).getPropertyValue(styleString) //w3c方法
    其中node为你要查询的节点对象 styleString为 如'top' 或'background-color' 此类属性名 而不是js中的backgroundColor 之类的
    ie的话 用 node.currentStyle[styleString]  但这个styleString 要用 'backgroundColor' 这种格式取

    记得 如果你没有 在node.style.属性名='' 这样显式的在js中赋值或内联style赋值, 你用node.style. 是取不到值的 必须使用上面的方法。

    上面的改成:

    elem=document.getElementById('id');

    var xpos= document.defaultView.getComputedStyle(elem,null).getPropertyValue('left');
    var ypos= document.defaultView.getComputedStyle(elem,null).getPropertyValue('top');
    var xpos=parseInt(xpos);
    var ypos=parseInt(ypos);

    就可以了。

  • 相关阅读:
    VueJS
    Nacos 微服务注册发现配置中心
    精简自己20%的代码(异常的处理)
    lazarus 检测内存泄漏
    winsocket练习一 阻塞与select模型
    js原型链解析
    块元素 父子外边距现象
    行高的继承
    行内元素(文字)垂直平居中
    本地文件播放
  • 原文地址:https://www.cnblogs.com/youxin/p/3942357.html
Copyright © 2011-2022 走看看