仅仅是学习html、css和javascript,就得到了在我的代码中使用<abbr>标记的疯狂想法,以及一个scrollspy.js (来自引导)的设置,它监视查看的段落并显示缩写/缩略词的定义。
由于我刚刚了解了javascript的基本原理,我想知道脚本本身是否可能这样做,还是需要进行一些修改(如果需要,请发布一个代码示例thx!)
发布于 2014-09-24 18:31:21
如果您查看scrollspy.js的源,实际上看不到任何对标头的引用。它的工作方式是查看导航链接和相应的元素,寻找内容元素与导航之间关系的线索。下面是它在文档中的外观
用于导航
<a href="#fat">@fat</a>代表这一节
<h4 id="fat">@fat</h4>现在要考虑的一件事是,<h4>元素是块级的,所以它们占据了整个行。内联元素可以位于同一条线上,因此可能无法看到应该根据可见部分突出显示哪个定义。对于您想要做的事情,我认为您需要创建自己的部分JavaScript。
这里有一种方法(虽然它需要一些调整来满足您的确切需求,它支持内联的abbr元素,甚至每行有多个定义)(下面是一个工作演示)
下面是JavaScript:
var mapTerms = function () {
/*grab all of the <abbr>s with terms associated with them, they can move anytime the browser is resized*/
var terms = [];
$('abbr[data-term]').each(function () {
var term = $(this);
terms.push({
term: term.data('term'),
height: term.offset().top,
visible: false,
element: term
});
});
return terms;
},
terms = [],
/*Keep a globally accessible list*/
$body = $('body'); /*need a reference to the body for performance*/
$(window).on('scroll', function () {
/*listen to the scroll event*/
var height = $(document).scrollTop(),
i;
for (i = 0; i < terms.length; i++) {
if (terms[i].visible) {
if (terms[i].height < height || terms[i].height > (height + 50)) {
terms[i].visible = false;
terms[i].element.removeClass('defined');
$('div[data-term=' + terms[i].term + ']').hide();
}
} else {
if (terms[i].height > height && terms[i].height < (height + 50)) {
terms[i].visible = true;
terms[i].element.addClass('defined');
$('div[data-term=' + terms[i].term + ']').show();
}
}
}
}).on('resize', function () {
/*listen to the resize event*/
console.log('mapping...');
terms = mapTerms();
}).trigger('resize').trigger('scroll');下面是一些CSS,它隐藏并突出了术语及其定义(以及使定义可见):
abbr.defined {
background: red;
}
.definition {
display: none;
}
#definitions {
position: fixed;
}它的工作方式是查找具有指向如下完整定义的数据元素的<abbr>:
<abbr data-term='blog' title='Webblog'>blog</abbr>每一个点都指向一个包含定义的div (示例中底部的侧栏中填充)。
<div class='definition' data-term='blog'>
<h4>Blog</h4>
<p>A blog (a truncation of the expression weblog) is a discussion or informational site published on the World Wide Web and consisting of discrete entries ("posts") typically displayed in reverse chronological order (the most recent post appears first).</p>
<p><i>source <a href='http://en.wikipedia.org/wiki/Blog'>Wikipedia</a></i></p>
</div>然后,当您调整浏览器的大小时,onResize代码构建了一个包含所有<abbr>元素的映射,当您滚动时,onScroll代码看起来是您当前的位置,并试图找出每个术语是否是可见的(它使用的是一个非常简单的可视定义,它位于浏览器的前50个像素内)。在生产中,您可能希望测试它是在滚动顶部和窗口高度之间,还是考虑到用户向下滚动以读取更多定义,但将该术语从屏幕上移出。这是一个棘手的事情,得到100%的权利,但这应该会使你进一步。
https://stackoverflow.com/questions/25827570
复制相似问题