简体   繁体   English

如何切换外部CSS文件?

[英]How do I switch external CSS files?

I've got a couple books that I'm reading on AJAX, but still quite new. 我有几本书,我正在阅读AJAX,但还是很新的。 All the tutorials and these books have the ubiquitous examples of: an auto-populating search bar and an asynchronous form validator. 所有教程和这些书都有无处不在的例子:自动填充搜索栏和异步表单验证器。 Those are both great, but not what I'm looking for. 这些都很棒,但不是我想要的。 Specifically, I want to click a button and switch the external CSS file in my header include. 具体来说,我想单击一个按钮并在我的标题包中切换外部CSS文件。 Is this possible? 这可能吗? Well... I know it's possible, but how do you do it? 嗯......我知道这是可能的,但是你怎么做的?

PS: I have jQuery in this project, so if there is something built in from there, even better! PS:我在这个项目中有jQuery,所以如果有内置的东西,那就更好了!

PPS: I'm realizing I have not included important information (don't shoot me!): PPS:我意识到我没有收录重要信息(不要开枪!):

  1. The final goal of this will be to have a user settings section where the user can click a radio button and decide the color scheme they want to use for our app. 最终目标是拥有一个用户设置部分,用户可以单击单选按钮并确定他们想要用于我们的应用程序的颜色方案。 So we will eventually have something like 8 different CSS styles to choose from. 所以我们最终会有8种不同的CSS样式可供选择。 Not sure if this will alter the best method to achieve this. 不确定这是否会改变实现这一目标的最佳方法。

  2. The user is logging into their account and changing their setting there. 用户正在登录他们的帐户并在那里更改他们的设置。 I want their changes to 'stick' until they decide to change the stylesheet again. 我希望他们的更改能够“坚持”,直到他们决定再次更改样式表。 I can do this manually in MySQL as we have a table called stylesheets with the various user stylesheets numbered... so in actuality, what I'm needing to do is change that MySQL value asynchronously so the CSS is immediately loaded. 我可以在MySQL中手动执行此操作,因为我们有一个名为样式表的表,其中各种用户样式表都已编号...所以实际上,我需要做的是异步更改MySQL值,以便立即加载CSS。

Add an id attribute to the CSS link tag to manipulate the tag using JavaScript: 将一个id属性添加到CSS link标记以使用JavaScript操作标记:

<link id="cssfile" href="css/avocado.css" type="text/css" rel="stylesheet">

The Javascript to set the href attribute resembles: 设置href属性的Javascript类似于:

document.getElementById('cssfile').href = 'css/carrot.css';

Colours could be tweaked by the user, by clicking a link: 用户可以通过单击链接调整颜色:

<a href="#"
 onclick="document.getElementById('cssfile').href='css/carrot.css';">Carrots</a>

By changing the media type, this could also allow users to quickly change print layouts, the preferred layout on mobiles (or tablets), and more. 通过更改媒体类型,这还可以允许用户快速更改打印布局,移动设备(或平板电脑)上的首选布局等。

This solution does not require jQuery. 此解决方案不需要jQuery。

See also: http://www.webmasterworld.com/forum91/4554.htm 另见: http//www.webmasterworld.com/forum91/4554.htm

Stylesheet Switcher in jQuery. jQuery中的样式表切换器。

In response to the 'newbie followup' comment, I will try to make it a little more instructional. 为了回应“新手跟进”评论,我将尝试使其更具说明性。

The page I was playing with to test on while writing can be found here . 我可以在这里找到我正在玩的用于测试的页面。

Page Display 页面显示

You're going to want to have your current stylesheet displayed in a <link> tag in the <head> of each of your pages. 您将希望将当前样式表显示在每个页面的<head>中的<link>标记中。 The <link> tag will need an id for reference later in JavaScript. <link>标记需要一个id以供稍后在JavaScript中参考。 Something like: 就像是:

<?php 
  // Somewhere in the server side code, $current_stylesheet is read from the user's 
  // "preferences" - most likely from a database / session object
  $current_stylesheet = $user->stylesheet;
?>
<link href='<?php echo $current_stylesheet ?>' rel='stylesheet' type='text/css' id='stylelink' />

Changing the preference 改变偏好

Once you are displaying the users stylesheet, you need a way to change it. 显示用户样式表后,您需要一种方法来更改它。 Create a <form> that will send a request to the server when the user changes their stylesheet: 创建一个<form> ,当用户更改样式表时,它将向服务器发送请求:

<form method="GET" id="style_form" >
  <select name="stylesheet" id="styleswitch">
    <option value="css1.css">Black &amp; White</option>
    <option value="css2.css" selected="selected">Shades of Grey</option>
   </select>
   <input value='save' type='submit' />
</form>

Server Side 服务器端

Now, without jQuery, submitting this form should GET (you could change it to POST if you like) stylesheet={new stylesheet} on the current page. 现在,如果没有jQuery,提交此表单应该在当前页面上获取(如果您愿意,可以将其更改为POST) stylesheet={new stylesheet} So somewhere in your bootstrap / sitewide include file, you do a check for it, a php sample: 所以在你的bootstrap / sitewide包含文件的某个地方,你做了一个检查,一个php示例:

$styles = array(
  'css1.css' => 'Black &amp; White',
  'css2.css' => 'Shades of Grey',
);

if (!empty($_GET["sytlesheet"]) {
  // VALIDATE IT IS A VALID STYLESHEET - VERY IMPORTANT
  // $styles is the array of styles:
  if (array_key_exists($_GET["stylesheet"], $styles)) {
    $user->stylesheet = $_GET["stylesheet"];
    $user->save();
  }
}

Live Preview 实时预览

At this point, you have a functioning styleswitcher for the lame people without javascript. 在这一点上,你有一个功能齐全的styleswitcher为没有javascript的跛脚的人。 Now you can add some jQuery to make this all happen a little more elegantly. 现在你可以添加一些jQuery来使这一切更优雅地发生。 You'll want to use the jQuery Form Plugin to make a nice ajaxForm() function, that will handle submitting the form. 你将需要使用jQuery Form Plugin来创建一个很好的ajaxForm()函数,它将处理提交表单。 Add the jQuery and jQuery Form library to the page: 将jQuery和jQuery表单库添加到页面:

<script type='text/javascript' src='/js/jquery.js'></script>
<script type='text/javascript' src='/js/jquery.form.js'></script>

Now that we have the libraries included - 现在我们已经包含了库 -

$(function() {
  // When everything has loaded - this function will execute:


  $("#style_form").ajaxForm(function() {
    // the style form will be submitted using ajax, when it succeeds:
    // this function is called:
    $("#thediv").text('Now Using: '+$('#styleswitch').val());
  });

  $("#styleswitch").change(function() {
    // When the styleswitch option changes, switch the style's href to preview
    $("#stylelink").attr('href', $(this).val());
    // We also want to submit the form to the server (will use our ajax)
    $(this).closest('form').submit();
  });

  // now that you have made changing the select option submit the form,
  // lets get rid of the submit button
  $("#style_form input[type=submit]").remove();
});

Here's an example that uses jQuery. 这是一个使用jQuery的例子。

<!DOCTYPE html>
<html>
    <head>
    <link rel="stylesheet" type="text/css" href="style1.css" />
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"
            type="text/javascript"></script>
        <script type="text/javascript">
            $(function(){
                $('#change-css').click(function(e){
                    e.preventDefault();
                    $('link[rel="stylesheet"]').attr('href', 'style2.css');
                });
            });
        </script>
    </head>
    <body>
        <a id="change-css" href="#">change css</a>
    </body>
</html>

The operative line is $('link[rel="stylesheet"]').attr('href', 'style2.css'); 操作行是$('link[rel="stylesheet"]').attr('href', 'style2.css'); . This finds any <link> tag that has rel="stylesheet" and changes its href attribute to style2.css . 这将找到任何具有rel="stylesheet" <link>标记,并将其href属性更改为style2.css

It has nothing to do with Ajax. 它与Ajax无关。 It has everything to do with JS and DOM manipulation (Some key words to search for tutorial). 它与JS和DOM操作(搜索教程的一些关键词)有关。
I am using Mootools, which is a JS library and it has a built in function for that. 我正在使用Mootools,这是一个JS库,它有一个内置的功能。
If doing it manually is your thing, then I would simply add a <link> element to the <head> or adjust the href attribute of an existing <link> element. 如果手动执行此操作,那么我只需将<link>元素添加到<head>或调整现有<link>元素的href属性。

 <link rel="stylesheet" href="http://sstatic.net/so/all.css?v=6063" id='bobo'>
...
...
...
<script>document.getElementById('bobo').href="http://my.doamin.com/new.css";</script>

You could also load both CSS files and preface the all of the selectors on the second file with a body classname. 您还可以使用正文类名加载两个CSS文件并在第二个文件上添加所有选择器。

body.secondsheet {}
body.secondsheet a {}
body.secondsheet hr {}

Then all you have to do is add/remove the "secondsheet" class to the body tag to switch stylesheets. 然后,您所要做的就是在body标签中添加/删除“secondsheet”类以切换样式表。

To add a new css file to a page just create a new <link> tag: 要向页面添加新的css文件,只需创建一个新的<link>标记:

function addCss (url) {
    var s = document.createElement('link');
    s.rel = 'stylesheet';
    s.type = 'text/css';
    s.href = url;
    document.getElementsByTagName('head')[0].appendChild(s);
}

addCss('http://path/to/stylesheet.css');

To remove a css file from a page just remove the <link> to it: 要从页面中删除css文件,只需删除<link>即可:

function removeCss (search) {
    var css = document.getElementsByTagName('link');
    for (var i=0;i<css.length;i++) {
        var c = css[i];
        if (c.rel === 'stylesheet' || c.type === 'text/css') {
            if (c.href && c.href.match(search)) {
                c.parentNode.removeChild(c);
            }
        }
    }
}

// Remove all css that contains 'mycss_', can use regexp if necessary:
removeCss(/mycss_.*\.css/);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM