[英]Append element to parent and position based on parent's current width
I have a progress bar that indicates the scroll progress for a page. 我有一个进度条,指示页面的滚动进度。 So if I scroll the page half way down the progress bar width is set to 50%, so it is constantly changing based on where I am on the page. 因此,如果我将页面向下滚动一半,进度条的宽度将设置为50%,因此它会根据我在页面上的位置而不断变化。
(function(){
var $w = $(window);
var $prog = $('.progress-bar');
var wh, h, sHeight;
function setSizes(){
wh = $w.height();
h = $('#page-content-wrapper').height();
sHeight = h - wh;
}
setSizes();
$w.on('scroll', function(){
var perc = Math.max(0, Math.min(1, $w.scrollTop()/sHeight));
updateProgress(perc);
}).on('resize', function(){
setSizes();
$w.trigger('scroll');
});
function updateProgress(perc){
$prog.css({width : perc*100 + '%'});
}
}());
What I would like to do is append an element to visually indicate the bookmarked position in relation to the progress bar. 我想做的是附加一个元素,以可视方式指示相对于进度条的书签位置。 So let's say I want to add an asterix (*) below the progress bar when I click the bookmark button/link. 假设我要在单击书签按钮/链接时在进度条下方添加一个星号(*)。
To do this I need a way of using the current progress bar width and use that to set the appended element position, which I have, though not sure how to apply that in append context. 为此,我需要一种使用当前进度条宽度的方法,并使用它来设置附加元素的位置,尽管我不确定如何将其应用于附加上下文。
$('#bookmark').on("click", function() {
$(".progress-bar").append("<div style='position:absolute; left:xxxx%'>*</div>");
});
Thank you 谢谢
I rewrote you code: 我重写了您的代码:
var w = $(window);
var prog = $('.progress-bar');
var wh, h, sHeight;
function setSizes() {
wh = w.height();
h = $('.text')
.height();
sHeight = h - wh;
}
setSizes();
w.on('scroll', function () {
var perc = Math.max(0, Math.min(1, w.scrollTop() / sHeight));
updateProgress(perc);
})
.on('resize', function () {
setSizes();
w.trigger('scroll');
});
function updateProgress(perc) {
prog.css({
width: parseInt(perc * 100, 10) + '%'
});
if (perc <= 0) $('#c')
.hide();
else $('#c')
.show(500);
}
$('#c')
.hide();
$('#c')
.click(function () {
$('.star')
.remove();
});
$('.bk')
.click(function () {
var add = "";
l = prog.width() - 10;
t = prog.height() / 2;
add = "<div class=\"star\" style=\" left:";
add += l;
add += "px; top:";
add += t;
add += "px;\">*</div>";
$('body')
.append(add);
});
You are using double quotes inside the double quotes in append() 您在append()中的双引号内使用双引号
It should be like this, 应该是这样
$(".progress-bar").append("<div style='position:absolute; left:xxxx%'>*</div>");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.