<html>
<head>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<style type="text/css">
* {
padding: 0px;
margin: 0px;
}
#hello {
width: 1000px;
height: 970px;
background-color: #7996e6;
position: relative;
margin: auto;
}
</style>
<script type="text/javascript">
var getRandomColor = function() {
return '#' + ( function( color ) {
return ( color += '0123456789abcdef' [ Math.floor( Math.random() * 16 ) ] )
&& ( color.length == 6 ) ? color : arguments.callee( color );
} )( '' ); }
z_index = 10000
$( document ).ready( function() {
$( document ).on( "click", ".element", function ( event ) {
event = event || window.event;
var x = event.offsetX || event.originalEvent.layerX;
var y = event.offsetY || event.originalEvent.layerY;
//alert( "width: " + width + ", x: " + x + ", y: " + y )
var width = parseFloat( $( this ).width() );
var height = parseFloat( $( this ).height() );
z_index += 1;
var new_element = $( "<div></div>" ).css( {
"width" : width / 2,
"height" : height / 2,
"background-color" : getRandomColor(),
"position": "absolute",
"z-index": z_index,
} ).attr( "class", "element" )
if ( 0 <= x && x <= width / 2 && 0 <= y && y <= height / 2 ) {
new_element.css( {
"left" :0,
"top": 0,
} ).appendTo( this )
} else if ( width >= x && x >= width / 2 && 0 <= y && y <= height / 2 ) {
new_element.css( {
"left" : width / 2,
"top": 0,
} ).appendTo( this )
} else if ( 0 <= x && x <= width / 2 && height / 2 <= y && y <= height ) {
new_element.css( {
"left" :0,
"top": height / 2,
} ).appendTo( this )
} else {
new_element.css( {
"left" : width / 2,
"top": height / 2,
} ).appendTo( this )
}
event.stopPropagation();
} );
} );
</script>
</head>
<body>
<div class="element" id="hello"></div>
</body>
<script type="text/javascript">
</script>
</html>
parseFloat() 函数可解析一个字符串,并返回一个浮点数。
该函数指定字符串中的首个字符是否是数字。如果是,则对字符串进行解析,直到到达数字的末端为止,然后以数字返回该数字,而不是作为字符串。
appendTo() 方法在被选元素的结尾(仍然在内部)插入指定内容。
语法:$(content).appendTo(selector)
event.stopPropagation(); 使用stopPropagation()
函数可以阻止当前事件向祖辈元素的冒泡传递,也就是说该事件不会触发执行当前元素的任何祖辈元素的任何事件处理函数。