开发者

javascript modify style of an element

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");
    newd开发者_运维知识库iv.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>


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/


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".


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.


<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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜