简体   繁体   English

如何将页面内的样式更改应用到其他页面?

[英]How can I apply the style change made within the page to other pages?

There is an in-site language change script with google translate.有一个带有谷歌翻译的现场语言更改脚本。 I made the menu of this script and there are flags of countries belonging to languages in the menu.我制作了这个脚本的菜单,菜单中有属于语言的国家的标志。 These flags change according to the selected languages.这些标志会根据所选语言而变化。 I want these flags to be the same on other pages when the page changes.当页面更改时,我希望这些标志在其他页面上相同。

My menu style changer and cookie script:我的菜单样式更改器和 cookie 脚本:

$(document).ready(function(){
  function setCookie(lang){
    document.cookie = `lang=${lang}; expires=Mon, 1 Jan 2100 00:00:00 GMT`;
  };
  $("#tr").click(function(){
    $("#lang-here").removeClass();
    $("#lang-here").addClass('selected-lang');
    $("#lang-here").text("Türkçe");
    setCookie("tr");
  });
  $("#en").click(function(){
    $("#lang-here").removeClass();
    $("#lang-here").addClass('selected-langen');
    $("#lang-here").text("English");
    setCookie("en");
  });
  $("#de").click(function(){
    $("#lang-here").removeClass();
    $("#lang-here").addClass('selected-langde');
    $("#lang-here").text("Deutsch");
    setCookie("de");
  });
  $("#ja").click(function(){
    $("#lang-here").removeClass();
    $("#lang-here").addClass('selected-langja');
    $("#lang-here").text("日本");
    setCookie("ja");
  });
  $("#fr").click(function(){
    $("#lang-here").removeClass();
    $("#lang-here").addClass('selected-langfr');
    $("#lang-here").text("Français");
    setCookie("fr");
  });
  $("#es").click(function(){
    $("#lang-here").removeClass();
    $("#lang-here").addClass('selected-langes');
    $("#lang-here").text("Español");
    setCookie("es");
  });
  $("#ru").click(function(){
    $("#lang-here").removeClass();
    $("#lang-here").addClass('selected-langru');
    $("#lang-here").text("Pусский");
    setCookie("ru");
  });
})

If my use of this script is correct, I would appreciate it if you could tell me how to show the style changes.如果我对这个脚本的使用是正确的,如果您能告诉我如何显示样式更改,我将不胜感激。

I've done something similar in the past and have tried to work it for this question.我过去做过类似的事情,并试图解决这个问题。

First I have a basic javascript cookie controller which is used to read/write the Google Translation cookie:首先我有一个基本的 javascript cookie controller 用于读/写谷歌翻译 cookie:

/**
 * Basic javascript cookie controller.
 *
 * @type {Object}
 */
window.Cookies = {

    /**
     * Get cookie value by key
     *
     * @param {String} key
     * @return {String}
     */
    get: function( key ) {
        return decodeURIComponent( document.cookie.replace( new RegExp( '(?:(?:^|.*;)\\s*' + encodeURIComponent( key ).replace( /[\-\.\+\*]/g, '\\$&' ) + '\\s*\\=\\s*([^;]*).*$)|^.*$' ), '$1' ) ) || null;
    },

    /**
     * window.Cookies.set( key, value, end, path, domain, secure )
     *
     * @param {String} key Cookie name
     * @param {String} value Cookie value
     * @param {Number|String|Date|NULL} end The max-age in seconds
     * @param {String|NULL} path If not specified, defaults to the current path of the current document location
     * @param {String|NULL} domain If not specified, defaults to the host portion of the current document location
     * @param {Boolean|NULL} secure Cookie will be transmitted only over secure protocol as https;=
     *
     * @return {Void}
     */
    set: function( key, value, end, path, domain, secure ) {
        if ( !key || /^(?:expires|max\-age|path|domain|secure)$/i.test( key ) ) {
            return false;
        }
        let expires = '';
        if ( end ) {
            switch ( end.constructor ) {
                case Number:
                    expires = end === Infinity ? '; expires=Fri, 31 Dec 9999 23:59:59 GMT' : '; max-age=' + end;
                    break;
                case String:
                    expires = '; expires=' + end;
                    break;
                case Date:
                    expires = '; expires=' + end.toUTCString();
                    break;
            }
        }
        document.cookie = encodeURIComponent( key ) + '=' + encodeURIComponent( value ) + expires + ( domain ? '; domain=' + domain : '' ) + ( path ? '; path=' + path : '' ) + ( secure ? '; secure' : '' );
        return true;
    },

    /**
     * Remove cookie by key
     *
     * @param {String} key
     * @param {String} path
     * @param {String} domain
     * @return {Void}
     */
    remove: function( key, path, domain ) {
        if ( !key || !this.has( key ) ) {
            return false;
        }
        document.cookie = encodeURIComponent( key ) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT' + ( domain ? '; domain=' + domain : '') + ( path ? '; path=' + path : '');
        return true;
    },


    /**
     * Check if key exists in cookie
     *
     * @param {String} key
     * @return {Boolean}
     */
    has: function( key ) {
        return ( new RegExp( '(?:^|;\\s*)' + encodeURIComponent( key ).replace( /[\-\.\+\*]/g, '\\$&' ) + '\\s*\\=' ) ).test( document.cookie );
    },

    /**
     * Return array of cookie keys
     *
     * @return {Array}
     */
    keys: function() {
        let keys = document.cookie.replace( /((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, '' ).split( /\s*(?:\=[^;]*)?;\s*/ );
        for ( let i = 0; i < keys.length; i++ ) {
            keys[ i ] = decodeURIComponent( keys[ i ] );
        }
        return keys;
    }
};

We then have the code that handles the click events and setting on load:然后我们有处理点击事件和加载设置的代码:

( function( $ ) {
    'use strict';

    /**
     * The language code that the site uses by default. Tries to grab it from <html lang="{value}"> but will fallback to English.
     * 
     * @var {String} cookieKey
     */
    const sourceLang = $( 'html' ).attr( 'lang' ) || 'en'; // Change as needed

    /**
     * @var {jQuery} $selector
     */
    const $selector = $( '#lang-here' );

    /**
     * A list of the avialable languages {langCode} => {langLabel}.
     * 
     * @var {Object} langs
     */
    const langs = {
        tr: 'Türkçe',
        en: 'English',
        de: 'Deutsch',
        ja: '日本',
        fr: 'Français',
        es: 'Español',
        ru: 'Pусский'
    };

    /**
     * This is the cookie that's used by the Google Translator.
     * 
     * @var {String} cookieKey
     */
    const cookieKey = 'googtrans';

    /**
     * Set the language selector class/text and set the Google Translator cookie.
     * 
     * @param {String} langCode
     * @param {String} langLabel
     */
    function setLang( langCode, langLabel ) {
        $selector.removeClass( function( index, css ) {
            return ( css.match( /(^|\s)selected-lang\S+/g ) || [] ).join( ' ' );
        } ).addClass( `selected-lang${langCode}` );

        $selector.text( langLabel );

        Cookies.set( cookieKey, `/${sourceLang}/${langCode}`, null, '/' );
        Cookies.set( cookieKey, `/${sourceLang}/${langCode}`, null, '/', '.' + window.location.host );
    }

    // Get language on load.
    const current = ( Cookies.get( cookieKey ) || `/${sourceLang}/${sourceLang}` ).replace( /^\/[a-z]{2}\//i, '' );

    // Set lang on load.
    setLang( current, langs[ current ] );

    // Handle click events.
    for ( var key in langs ) {
        $( `#${key}` ).on( 'click' , {
            langCode: key,
            langLabel: langs[ key ]
        }, function( event ) {
            setLang( event.data.langCode, event.data.langLabel )
        } );
    }

} )( jQuery );

I've put an example together here: https://jsfiddle.net/thelevicole/f517wxp2/我在这里举了一个例子: https://jsfiddle.net/thelevicole/f517wxp2/

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

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