Javascript Draw line with jQuery
Please see my code here http://jsbin.com/ijoxa3/edit
var drawHorizondalLine = function(x1,y1,x2,y2, color) {
var width = Math.abs(x1 - x2);
var posX = (x1 > x2) ? x1 : x2;
var id ='c_'+new Date().getTime()
var line = "<div id='"+id+"'class='line'> </div>";
$('body').append(line);
$('#'+id).css({
left: posX,
开发者_StackOverflow中文版 top: y1,
width: width,
position:'absolute',
backgroundColor: color
});
};
$(document).ready(function() {
drawHorizondalLine(0, 10, 200, 10, '#a00');
drawHorizondalLine(0, 50, 100, 50, '#0a0');
});
<style>
.line{
padding;1px;
}
</style>
<body>
<p id="hello">Hello World</p>
</body>
</html>
The function call drawHorizondalLine(0, 10, 200, 10, '#a00');
is suppose to draw a line form the top left corner of the page, 100px in length, but the the line appear to start from the last div of the body.
Where is the mistake?
var posX = (x1 > x2) ? x1 : x2;
should be
var posX = (x1 < x2) ? x1 : x2;
Working demo is here
精彩评论