我正在尝试为我的页面创建一个 Facebook 共享按钮,可以通过选项卡索引并按 Enter 键进行访问(以实现可访问性)。我创建的许多解决方案都使用 JavaScript,并且只有在退出共享按钮后才会加载我的脚本。
到目前为止我已经创建了这个按钮。
<a tabindex="0" class="fb-share-button" href="javascript:window.location=%22http://www.facebook.com/sharer.php?u=%22+encodeURIComponent(document.location)+%22&t=%22+encodeURIComponent(document.title)" data-layout="button_count">
<img src="/sites/all/themes/saralee/images/icon-facebook.png" alt="facebook icon">
</a>
这几乎给出了期望的结果,除了我需要它在新选项卡或 iframe 中打开。我无法通过保留有效的网址来做到这一点。 (因为上面的按钮解析当前的 url)。使用 target="_blank"
不起作用。
最佳答案
快速说明 - 最佳选择是在服务器上构建 URL 并将其作为 HTML 的一部分提供,如果您因任何原因无法执行此操作,请使用下面的 JavaScript 选项。
除了下面的 URL 之外的所有其他点对于让您的共享“按钮”易于访问都很重要。
不要在按钮上使用内联函数,而是在单独的 JavaScript 函数中构建 URL,然后将其应用于文档加载。
JS
var URL = "http://www.facebook.com/sharer.php?u=%22+encodeURIComponent(document.location)+%22&t=%22+encodeURIComponent(document.title)";
var elements = document.getElementsByClassName("fb-share-button");
elements[0].setAttribute("href", URL); //using [0] to get first element, would be better to use an ID or simply **build the URL on the server before loading the page** and serve it as part of the HTML.
HTML
<a target="_blank" class="fb-share-button" href="fallback URL In Case Of JS Failure" data-layout="button_count">
<img src="/sites/all/themes/saralee/images/icon-facebook.png" alt=""/>
<span class="visually-hidden">Share This Page on Facebook (opens in new window)</span>
</a>
CSS
.visually-hidden {
position: absolute !important;
height: 1px;
width: 1px;
overflow: hidden;
clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
clip: rect(1px, 1px, 1px, 1px);
white-space: nowrap; /* added line */
}
因为你不再设置window.location
使用target="_blank"
将按预期工作( window.location
覆盖链接的功能)。
另请注意,我删除了 tabindex
因为链接默认情况下是可聚焦的(因此不需要)。
我还更改了alt
描述为“”并添加了“视觉隐藏”<span>
包含链接的目的。
我已经包含了 CSS,通过将该类应用于某个项目来制作“视觉隐藏”的内容,因为它是您的辅助功能工具包中的一个有用工具!
请注意我如何在括号内指示链接“在新窗口中打开”,以便让屏幕阅读器了解此链接的行为。
空 alt
标签用于将图像标记为装饰性(确保它为空且不为空,即 alt=""
NOT alt
)。
屏幕阅读器仍然可以访问视觉隐藏文本,但不会以视觉方式显示。
关于javascript - 创建易于访问的 Facebook 分享按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60232947/