I'm trying to create a bookmarking feature for my site, so when someone clicks on "set bookmark" then they click on a line of text, it will place a bookmark image to the left of that line. (i'll then save the coor to a cookie, but i can do that without help)
One way I thought about doing it was when the person clicked on a line of text in a paragraph, have it grab the Y coordinate of the place the person clicked, then have that number rounded down to the nearest number divisible by 20. The line height of each paragraphs is 20px, so if you rounded the Y coordinates down, then you would get the top position for that single line inside the paragraph they clicked.
So I think it would go like this: when someone clicks on a line of text in a paragraph, it will get the index of that paragraph, so if it's the 4th P down the page, the index will be 3, then it will get the Y coordinates开发者_Python百科 of where the user clicked, then round that number down to the nearest number divisible by 20, then place the image to the left of that paragraph with the TOP position of the image being the rounded Y coordinate.
Can anyone help me out with this? I'm kind of lost as you can see:
$('p').click(function(e) {
var myIndex = $(this).index()
var myIndexTop = myIndex.top()
var myIndexLeft = myIndex.left()
var offset = $(this).offset();
var y = e.pageY - this.offsetTop;
$('.bookMarkImg')
.left(myIndexLeft)
.top('round down to nearest num thats divisible by 20)
OR?
$('.bookMarkImg')
.css({'left': myIndexLeft, 'top' 'round down to nearest num thats divisible by 20'})
})
To round down to the nearest 20:
y = Math.floor(y / 20) * 20;
Also, .top()
and .left()
don't exist: you'll want:
$(this).offset().top
and$(this).offset().left
for getting the positions.css({left: ..., top: ...})
for setting them
Another thing is that if you only want one of these bookmark images to be floating around, depending on where you click, then you'll probably want to put the <img>
at the <body>
level (at the end), and positioned absolutely, so it is free to move around the entire document. Then, don't bother subtracting the offset of the paragraph from the y
coordinate.
Sample code:
$('p').click(function (e) {
var offset = $(this).offset();
var top = Math.floor(e.pageY / 20) * 20;
$('.bookMarkImg').css({
left: offset.left,
top: top
}).show();
});
See a working demo: http://jsfiddle.net/upgBa/
Note: You may have to consider any padding/margin/border you have on the paragraphs and the body though, which could throw off the calculations (just subtract the "top" portions of these).
精彩评论