本文介绍了如何使用JavaScript动态设置DIV元素的左和顶CSS定位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想手动创建一个 div 元素,稍后使用JavaScript添加一些CSS样式。我创建了一个 div 元素并用JavaScript改变了它的样式。问题是,一些CSS样式不起作用。

I want to create a div element manually and later add some CSS styling to it using JavaScript. I created a div element and changed it's style with JavaScript. The problem is, some CSS styles do not work.

颜色背景 width height )这些属性工作正常,但是( zIndex top left )属性不起作用。我想知道为什么会发生这种情况,以及如何纠正它。

(color, background, width, height) those properties worked fine but the (zIndex, top, left) properties do not work. I want to know why this happens and how to correct it.

这是我的JavaScript代码:

this is my JavaScript code:

function css()
{    
    var element = document.createElement('div');
    element.id = "someID";
    document.body.appendChild(element);

    element.appendChild(document.createTextNode
     ('hello this javascript works'));

    // these properties work
    document.getElementById('someID').style.zIndex='3';
    document.getElementById('someID').style.color='rgb(255,255,0)';
    document.getElementById('someID').style.background='rgb(0,102,153)';
    document.getElementById('someID').style.width='700px';
    document.getElementById('someID').style.height='200px';

    //these do not work
    document.getElementById('someID').style.left='500px';
    document.getElementById('someID').style.top='90px';
}

这是我的相关HTML代码

this is my relevant html code

<input type="submit" name="cssandcreate" id="cssandcreate" value="css"  onclick="css();"/>


推荐答案

top CSS样式设置不起作用,因为您必须首先设置 position 属性。如果未设置 position 属性,请设置 left 顶部样式将没有影响。 position 属性具有以下设置:

The left, and top CSS style settings aren't working because you must first set the position property. If the position property is not set, setting the left and top styles will have no affect. The position property has these settings:


  • static

  • 绝对

  • 固定

  • 相对

  • 初始

  • inherit

  • static
  • absolute
  • fixed
  • relative
  • initial
  • inherit

因此,尝试设置 position c $ c> left 和 top

So, try setting the position property before setting left and top:

object.style.position="absolute"

position 属性会影响后续设置如何定位您的元素。

The differences between the position properties affect how subsequent settings position your elements.

这篇关于如何使用JavaScript动态设置DIV元素的左和顶CSS定位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 17:14