更好的引用文字:避免重复标记

Avatar of Chris Coyier
Chris Coyier

DigitalOcean 为您旅程的每个阶段提供云产品。立即开始使用 200 美元的免费额度!

better-pullquote-example

引用文字非常棒。它们可以真正吸引读者的注意力,并且是进行酷炫排版工作的一个绝佳机会。但在博客上,引用文字特别难以“实现”(明白了吗?!)。
这是因为 RSS 的缘故。在您自己的网站上,您可以使用任何您想要的标记来创建引用文字。也许是一个带有“pullquote”类的段落标签。但是当这些内容发送到 RSS 阅读器时,该标签要么会被删除,要么会被忽略。

查看演示

以下是传统引用文字的标记可能是什么样子

<p>Whether I shall turn out to be the hero of my own 
life, or whether that station will be held by anybody else, these pages 
must show. To begin my life with the beginning of my life, I record that 
I was born (as I have been informed and believe) on a Friday, at twelve 
o'clock at night. It was remarked that the clock began to strike, and I 
began to cry, simultaneously.</p>
<p class="pullquote">It was remarked that the clock began to strike, 
and I began to cry, simultaneously.</p>

由于您的类在 RSS 阅读器中没有任何意义,因此对于以这种方式阅读的人来说,它看起来像是最后一句话重复了。尴尬

我们可以解决这个问题,并使用 jQuery 使我们的标记更加简洁。(哦,jQuery,有什么是你做不到的?亲亲。)这是我们新的、更简洁的标记

<p>Whether I shall turn out to be the hero of my own 
life, or whether that station will be held by anybody else, these pages 
must show. To begin my life with the beginning of my life, I record that 
I was born (as I have been informed and believe) on a Friday, at twelve 
o'clock at night. <span class="pullquote">It was remarked that the 
clock began to strike, and I began to cry, simultaneously.</span></p>

不同之处在于,我们不再重复要作为引用文字使用的部分,而是只需将该部分用一个带有“pullquote”类的 span 包裹起来。这个 span 是我们将需要使用 jQuery 来施展魔法的钩子。

我们需要在页面上包含 jQuery,然后编写一些简单的 JavaScript 代码来查找这些引用文字

<script src="js/jquery.js"></script>
<script>
  $(function() { 
	  $('span.pullquote).each(function(index) { 
		... do something ...
	  }); 
  });
</script>

上面的代码将等待 DOM 准备就绪,然后遍历整个页面,查找具有“pullquote”类的 span。现在我们需要添加魔法。首先,我们找到 span 的父元素,也就是它所在的段落,并将其设置为一个变量,因为我们将引用它两次(更快)。然后克隆该 span,并将其前置到同一个段落中。当然,我们添加了自己的类,可以用作样式化的钩子。

$(function() { 
	  $('span.pullquote).each(function() { 
		var $parentParagraph = $(this).parent('p'); 
		$parentParagraph.css('position', 'relative'); 
		$(this).clone() 
		  .addClass('pulledquote) 
		  .prependTo($parentParagraph); 
	  }); 
});

这实现了我们所需的功能:一个重复的元素(但仅在网站本身查看时),并具有一个独特的类来进行样式化。以下是一些“pulled”引用文字的 CSS 示例

.pulledquote {
	display: block;
	float: right;
	padding: 0 0 0 10px;
	margin: 0 0 10px 10px;
	width: 170px;
	font-size: 1.5em;
	line-height: 1.4em;
	text-align: right;
	color: #666;
	border-left: 3px solid #ccc;
}

演示中,我包含了两个单独的 jQuery 代码片段。一个用于将引用文字拉到左侧,另一个用于右侧。查看该页面的源代码以查看该代码。

 

其他文章/资源