我有一个用cloudconvert.com创建的html文件,我用java脚本包装它以突出显示其中的文本并使用JQuery scrollTop()函数滚动到第一个高亮显示。见例:
function doSearch2(text,color) {
if (window.find && window.getSelection) {
document.designMode = "on";
var sel = window.getSelection();
sel.collapse(document.body, 0);
while (window.find(text)) {
document.execCommand("HiliteColor", false, color);
sel.collapseToEnd();
}
document.designMode = "off";
} else if (document.body.createTextRange) {
var textRange = document.body.createTextRange();
while (textRange.findText(text)) {
textRange.execCommand("BackColor", false, color);
textRange.collapse(false);
}
}
var sel2 = document.getSelection();
var seltop = $(sel2.anchorNode.parentElement).offset().top;
var doccurrenttop = $('#page-container').scrollTop();
var scrollto = doccurrenttop + seltop - 70; // spce of 70px
if (scrollto < 0) { scrollto = 0; }
$('#page-container').scrollTop(scrollto);
}
doSearch2("Cross","yellow");
我尝试将doSearch2()函数插入到html文件的头部并将其加载到新的html文档中的iframe上。然后我从外部文档的按钮调用doSearch2()。
scrollTop工作正常,但在某些情况下(例如滚动到文档的底部和其他随机位置)。当我调试它时,我发现sel2(= document.getSelection())为零。
任何想法?
谢谢!
答案 0 :(得分:1)
好吧,它可能不适用于所有生成的脚本和html你在那里,但你可以看看我在这里为你做的这个jsfiddle。
将此添加到您的html页面:
$("img").imgCheckbox();
脚本
<a href="#0" class="cd-top">Top</a>
CSS
jQuery(document).ready(function($){
// browser window scroll (in pixels) after which the "back to top" link is shown
var offset = 300,
//browser window scroll (in pixels) after which the "back to top" link opacity is reduced
offset_opacity = 1200,
//duration of the top scrolling animation (in ms)
scroll_top_duration = 700,
//grab the "back to top" link
$back_to_top = $('.cd-top');
//hide or show the "back to top" link
$(window).scroll(function(){
( $(this).scrollTop() > offset ) ? $back_to_top.addClass('cd-is-visible') : $back_to_top.removeClass('cd-is-visible cd-fade-out');
if( $(this).scrollTop() > offset_opacity ) {
$back_to_top.addClass('cd-fade-out');
}
});
//smooth scroll to top
$back_to_top.on('click', function(event){
event.preventDefault();
$('body,html').animate({
scrollTop: 0 ,
}, scroll_top_duration
);
});
});