网页失去焦点标题变化效果

一、效果预览

在牛客网上看到的,效果如下:

即当切换到其它的页面即我们的网页失去焦点的时候,网页的标题就会被改变,当再切换回来的时候,网页标题就会被复原。

二、效果实现

 1.借助I-Miss-You.js

有现成的插件叫做I-Miss-You.js,在切换到其它页面的时候会改变当前页面的标题和图标,其github地址:https://github.com/Bahlaouane-Hamza/I-Miss-You

或者将下面的js代码拷走即可(需要注意的是这个插件实依赖于jQuery的。):

//     jquery.IMissYou.js 1.0.0

//     (c) 2015 Hamza Bahlaouane
//     jquery.IMissYou may be freely distributed under the MIT license.
//     For all details and documentation:
//     https://github.com/Bahlaouane-Hamza/I-Miss-You


// Uses CommonJS, AMD or browser globals to create a jQuery plugin.
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof module === 'object' && module.exports) {
        // Node/CommonJS
        module.exports = function( root, jQuery ) {
            if ( jQuery === undefined ) {
                // require('jQuery') returns a factory that requires window to
                // build a jQuery instance, we normalize how we use modules
                // that require this pattern but the window provided is a noop
                // if it's defined (how jquery works)
                if ( typeof window !== 'undefined' ) {
                    jQuery = require('jquery');
                }
                else {
                    jQuery = require('jquery')(root);
                }
            }
            factory(jQuery);
            return jQuery;
        };
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {
    "use strict";

    $.iMissYou = function (options) {

        // Options
        var opts = $.extend( {}, $.iMissYou.defaults, options),
            origTitle = document.title,
            favicon = $('head').find('link[rel$="icon"]');
        var origFavicon = favicon.attr("href");


        // Preload favicon
        if(opts.favicon.enabled)
            preloadFavicon();

        // Watch for visibilitychange event
        $(document).bind("visibilitychange", function(){

            // Change title
            $(document).prop('title', (document.hidden) ? opts.title : origTitle);

            // Change favicon too ?
            if(opts.favicon.enabled){
                if($(document).prop('hidden'))
                    changeFavicon();
                else
                    revertFavicon();
            }
        });

        // Utilities
        function changeFavicon() {
            favicon.attr("href", opts.favicon.src);
        }
        function revertFavicon() {
            favicon.attr("href", origFavicon);
        }
        function preloadFavicon() {
            $('<img/>')[0].src = opts.favicon.src;
        }

    };

    // Default
    $.iMissYou.defaults = {
        title: "I Miss you !",
        favicon: {
            enabled: true,
            src:'iMissYouFavicon.ico'
        }
    };

}));
View Code

简单使用的话只需要在页面中引入jquery.iMissYou.js,然后设定需要改变的标题,注意如果使用favicon的话需要本来就有一个favicon才可以。

一个简单的例子如下:

<!DOCTYPE html> 
<html>
    <head>
        <meta charset="UTF-8">
        <title>just for practice</title>
        <link rel="icon" href="imgs/icon.ico" type="image/x-icon"/> 
        <link rel="shortcut icon" href="imgs/icon.ico" type="image/x-icon"/> 
    </head>
    <body>



<!-- 网页内容.... -->


<!-- js依赖引入区 -->
<script type="text/javascript" src="../../js/jquery-2.2.3.js"></script>
<script type="text/javascript" src="js/jquery.iMissYou.js"></script>
<script type="text/javascript">
    
    $(function(){
    
        $.iMissYou({
            //当前网页被隐藏的时候要显示的标题
            title:"I Miss You.",
            //是否要切换icon, enabled布尔值设定是否开启,src用来设定使用的icon
            favicon: {
                enabled: true,
                src:'iMissYouFavicon.ico'
            }
        });
    
    });
    
</script>
        
    </body>
</html>

效果如下:

 

2. 自己造一个轮子

 对于看上去并不是很难的总是想重复造轮子,所以就尝试着写了一个不依赖jQuery的,代码如下:

/**
 * Author:CC11001100
 * 
 * Funny title
 * 
 *  用于网页失去焦点时改变成有趣的标题
 * 
 */
(function(){
    
    var vendorPrefix=getBrowserPrefix();
    var eventName=visibilityEvent(vendorPrefix);
    document.addEventListener(eventName,visibilityEventCallback);
    
    var oldTitle=document.title;
    function visibilityEventCallback(){
        if(document.hidden){
            oldTitle=document.title;
            document.title="(●—●)"+oldTitle;
        }else{
            document.title=oldTitle;
        }
    }
    

    /*------------------------ 下面的代码来自网络,用于解决浏览器兼容性问题 ----------------------------------*/
    
    // Get Browser-Specifc Prefix
    function getBrowserPrefix() {
    
          // Check for the unprefixed property.  
          if ('hidden' in document) {
            return null;
        }
    
        // All the possible prefixes.  
        var browserPrefixes = ['moz', 'ms', 'o', 'webkit'];
         
        for (var i = 0; i < browserPrefixes.length; i++) {
            var prefix = browserPrefixes[i] + 'Hidden';
            if (prefix in document) {
              return browserPrefixes[i];
            }  
        }
    
         // The API is not supported in browser.  
         return null;
    }
    
    // Get Browser Specific Hidden Property
    function hiddenProperty(prefix) {
        if (prefix) {
            return prefix + 'Hidden';
        } else {
            return 'hidden';
        }
    }
    
    // Get Browser Specific Visibility State
    function visibilityState(prefix) {
      if (prefix) {
        return prefix + 'VisibilityState';
      } else {
        return 'visibilityState';
      }
    }
    
    // Get Browser Specific Event
    function visibilityEvent(prefix) {
      if (prefix) {
        return prefix + 'visibilitychange';
      } else {
        return 'visibilitychange';
      }
    }    
    
})();

 使用的时候只需要将上面的js文件另存为,然后引入即可。

这一句即是设定当前网页“被隐藏”的时候网页标题显示的东西:

document.title="(●—●)"+oldTitle; 

github地址: https://github.com/BenDanChen/FunnyTitle

三、总结

优点:增加了网页的趣味性。

缺点:当同时打开了很多网页的时候,就会出现这种情况:

这可就尴尬了...

一个简单的解决办法是在本网站上只变化刚刚失去焦点的那部分,关于多个网页之间怎么协同,也许用cookie设定一个标志可以实现吧,只是一个设想,就不去实现了...

原文地址:https://www.cnblogs.com/cc11001100/p/6243329.html