javascript modify style of an element

北城余情 提交于 2020-01-16 13:04:32

问题


As a newbie to javascript I am trying to code a function that adds yellow divs to page (like post-its) wherever the user clicks. Event handling seems fine, but somehow the style properties I want are not applied. Here is my script :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript"> 
function get_position(e){
    //ie
    if(document.all){
        curX = event.clientX;
        curY = event.clientY;
    }
    //netscape 4
    if(document.layers){
        curX = e.pageX;
        curY = e.pageY;
    }
    //mozilla
    if(document.getElementById){
        curX = e.clientX;
        curY = e.clientY;
    }
}

function new_div(pobj,e){
    get_position(e);
    newdiv=document.createElement("div");
    newdiv.style.position="absolute";
    newdiv.style.left=curX+'px';
    newdiv.style.top=curY+'px';
    newdiv.style.color="yellow";
    document.body.appendChild(newdiv);
//  alert("new div");
}
</script>
</head>
<body onmousedown="new_div(this,event);">
</body>

</html>

回答1:


Some basic demo:

window.onclick = function ( e ) {
    if ( e.target.className === 'postit' ) { return; }
    var div = document.createElement( 'div' );
    div.contentEditable = true;
    div.className = 'postit';
    div.style.left = e.clientX + 'px';
    div.style.top = e.clientY + 'px';
    document.body.appendChild( div );
};

Live demo: http://jsfiddle.net/4kjgP/1/




回答2:


The div you are creating has no size so it won't be visible even if the rest of the code works as desired. Then, once you give it some size, there is no content so you still may not see it.

The color style attribute applies to text in the div and you have no text so you won't see any yellow. If you want a yellow block, you should set the background color to yellow (after you set a size) with .style.backgroundColor = "yellow".




回答3:


if you want to add yellow divs, you might be actually thinking of adding yellow colored divs? Code you are using should make text in them yellow. if you want bg to be yellow, use style.backgroundColor instead. Also give your div some width and height, or alternatively, give it some content, else it might now show.




回答4:


<div> with no content inside and no size will usually be skipped by browser rendering. You'll probably also need to put another element inside of it (like a <p> with lorem ipsum) to see something appear.

For real-time editing and playing with this stuff, check out JSFiddle

This also doesn't do what you want. Setting the color will make the text yellow, not the post it note effect. For that, use background. Check out this re-worked solution.



来源:https://stackoverflow.com/questions/7458425/javascript-modify-style-of-an-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!