Get a CSS value with JavaScript

前端 未结 9 1629
温柔的废话
温柔的废话 2020-11-21 07:55

I know I can set a CSS value through JavaScript such as:

document.getElementById(\'image_1\').style.top = \'100px\';

But, can I

9条回答
  •  南旧
    南旧 (楼主)
    2020-11-21 08:15

    As a matter of safety, you may wish to check that the element exists before you attempt to read from it. If it doesn't exist, your code will throw an exception, which will stop execution on the rest of your JavaScript and potentially display an error message to the user -- not good. You want to be able to fail gracefully.

    var height, width, top, margin, item;
    item = document.getElementById( "image_1" );
    if( item ) {
      height = item.style.height;
      width = item.style.width;
      top = item.style.top;
      margin = item.style.margin;
    } else {
      // Fail gracefully here
    }
    

提交回复
热议问题