我正在尝试在 Wordpress 中实现一个简单的基于切换的样式切换器。该解决方案最初是为 HTML 编写的。可以查到here .
可以在那里找到必要的 .js 文件。请参阅下面的 Vitch 评论,纠正 stylesheetToggle.js 文件中的一个错误。
这提供的是一个简单的文本链接,我可以将其放入模板中,在两个样式表之间切换,无需刷新页面,并与一个 cookie 链接,如果用户转到网站的其他位置,该 cookie 会记住用户的选择。
这就是我到目前为止所得到的(抱歉,我是根据我从创建风格切换器的大量尝试中学到的知识拼凑起来的)。
为了简单起见,所有文件都位于我的主题文件夹的根目录中。
我将其添加到我的functions.php中:
function wpb_adding_scripts() {
wp_register_script('stylesheetToggle', get_template_directory_uri() . '/stylesheetToggle.js', array('jquery'),'1.1', false);
wp_enqueue_script('stylesheetToggle');
}
add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );
function wpb_adding_styles() {
wp_register_style('contrast', get_stylesheet_directory_uri() . '/contrast.css');
wp_enqueue_style('contrast');
wp_register_style('white', get_stylesheet_directory_uri() . '/style.css');
wp_enqueue_style('white');
}
add_action( 'wp_enqueue_scripts', 'wpb_adding_styles' );
然后在我的index.php中添加(在顶部,在get_header(); ?>):
<?php wp_enqueue_script("stylesheetToggle"); ?>
在我的 header.php 中我添加了:
<link rel="stylesheet" type="text/css" href=" ... /style.css" title="white">
<link rel="alternate stylesheet" type="text/css" href=" ... /contrast.css" title="contrast">
<?php wp_enqueue_script("stylesheetToggle"); ?>
注意:样式表的 URL 必须是绝对路径。
这也出现在 header.php 中,位于“head”的末尾和“body”的开头之间:
<script>
jQuery.noConflict();
jQuery(document).ready(function($) {
$(function()
{
// Call stylesheet init so that all stylesheet changing functions
// will work.
$.stylesheetInit();
// This code loops through the stylesheets when you click the link with
// an ID of "toggler" below.
$('#toggler').bind(
'click',
function(e)
{
$.stylesheetToggle();
return false;
}
);
// When one of the styleswitch links is clicked then switch the stylesheet to
// the one matching the value of that links rel attribute.
$('.styleswitch').bind(
'click',
function(e)
{
$.stylesheetSwitch(this.getAttribute('rel'));
return false;
}
);
}
);
});
</script>
在我的相关模板文件中,我添加了:
<a href="#" id="toggler">Focus mode</a>
结果:现在可以了,感谢 Vitch 和 David。
页面网址:http://thiscouldbeparadise.org/change/
“焦点模式”应该切换可用的样式表。
最佳答案
我查看了您的网址,我想我可以看到问题所在...
尝试更改 styleswitcher 代码的第 25 行:
$('link[@rel*=style][title]')
致:
$('link[rel*=style][title]')
我认为 @
对于最新版本的 jQuery 来说不再是必需的,并且可能会导致问题(我编写了样式切换器代码,但那是很多年前的事了,自那以后 jQuery 发生了很大变化) 。当您更新 URL 时请告诉我,如有必要,我将更新我的脚本副本,这样其他人就不会遇到同样的问题...
我还注意到,在您的页面中,我当前无法看到您尝试添加的两个样式表(“默认”和“对比度”)。检查您是否也将它们正确添加到页面中...
关于Wordpress 中的 JavaScript 样式切换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25154425/