javascript修改元素的样式 [英] javascript modify style of an element
本文介绍了javascript修改元素的样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
作为一个新手的javascript我试图编写一个函数,添加黄色divs页面(像post-its)无论用户单击。事件处理似乎很好,但不知何故,我想要的样式属性不适用。这是我的脚本:
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>
推荐答案
一些基本演示:
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 );
};
在线演示: http://jsfiddle.net/4kjgP/1/
这篇关于javascript修改元素的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文