标签: Javascript

  • 无需插件 chrome浏览器在Console中网页自动刷新页面的Javascript代码

    无需插件 chrome浏览器在Console中网页自动刷新页面的Javascript代码

    • 打开网页后,按F12打开调试工具栏
    • 选择“控制台”,黏贴如下代码后,按回车。
    timeout = prompt("Set timeout (Second):");
    count = 0
    current = location.href;
    if (timeout > 0)
        setTimeout('reload()', 1000 * timeout);
    else
        location.replace(current);
    function reload () {
        setTimeout('reload()', 1000 * timeout);
        count++;
        console.log('每(' + timeout + ')秒自动刷新,刷新次数:' + count);
        fr4me = '<frameset cols=\'*\'>\n<frame src=\'' + current + '\'/>';
        fr4me += '</frameset>';
        with (document) { write(fr4me); void (close()) };
    }
    • 输入自动刷新的时间间隔(单位秒),即可实现自动刷新,直到你关掉页面或者手工刷新界面为止。
  • jquery css 实现网页下滑时,某个div保持页面为止不动

    最近在学seo,发现很多网站中都有这种的,页面下拉时某个div保持在页面的位置不动的效果,实现起来其实很简单,这边我们记录一下简单的代码

    jquery方法定义

        $.fn.smartFloat = function () {
            var position = function (element) {
                console.log(element);
                var top = element.position().top, pos = element.css("position");
                $(window).scroll(function () {
                    var scrolls = $(this).scrollTop();
                    if ((scrolls - 30) > top) {
                        if (window.XMLHttpRequest) {
                            element.css({
                                position: "fixed",
                                top: 0,
                                width: "100%",
                                "background-color": "#FFF",
                                "z-index": 1
                            });
                        } else {
                            element.css({
                                top: scrolls
                            });
                        }
                    } else {
                        element.css({
                            position: pos,
                            top: top
                        });
                    }
                });
            };
            return $(this).each(function () {
                position($(this));
            });
        };

    调用方法

    $(".post-view-ranking-wrap").smartFloat();
    
  • javascript代码实现 随机漂浮的广告图片 代码实例

    javascript代码实现 随机漂浮的广告图片 代码实例

    <!DOCTYPE html>
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            <title>js随机飘动的广告图片代码</title>
        </head>
        <body> 
           <div id="main" style="position:absolute;">
                <div style="text-align:right;cursor:pointer;" id="close">关闭</div>
                <a href="" target="_blank"><img src="图片地址.jpg" border="0" width="214" height="73" /></a>
            </div>
        </body>
    </html>
    <script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
    <script>
        <!--//公共脚本文件 main.js
        function addEvent(obj, evtType, func, cap) {
            cap = cap || false;
            if (obj.addEventListener) {
                obj.addEventListener(evtType, func, cap);
                return true;
            } else if (obj.attachEvent) {
                if (cap) {
                    obj.setCapture();
                    return true;
                } else {
                    return obj.attachEvent("on" + evtType, func);
                }
            } else {
                return false;
            }
        }
        function removeEvent(obj, evtType, func, cap) {
            cap = cap || false;
            if (obj.removeEventListener) {
                obj.removeEventListener(evtType, func, cap);
                return true;
            } else if (obj.detachEvent) {
                if (cap) {
                    obj.releaseCapture();
                    return true;
                } else {
                    return obj.detachEvent("on" + evtType, func);
                }
            } else {
                return false;
            }
        }
        function getPageScroll() {
            var xScroll, yScroll;
            if (self.pageXOffset) {
                xScroll = self.pageXOffset;
            } else if (document.documentElement && document.documentElement.scrollLeft) {
                xScroll = document.documentElement.scrollLeft;
            } else if (document.body) {
                xScroll = document.body.scrollLeft;
            }
            if (self.pageYOffset) {
                yScroll = self.pageYOffset;
            } else if (document.documentElement && document.documentElement.scrollTop) {
                yScroll = document.documentElement.scrollTop;
            } else if (document.body) {
                yScroll = document.body.scrollTop;
            }
            arrayPageScroll = new Array(xScroll, yScroll);
            return arrayPageScroll;
        }
        function GetPageSize() {
            var xScroll, yScroll;
            if (window.innerHeight && window.scrollMaxY) {
                xScroll = document.body.scrollWidth;
                yScroll = window.innerHeight + window.scrollMaxY;
            } else if (document.body.scrollHeight > document.body.offsetHeight) {
                xScroll = document.body.scrollWidth;
                yScroll = document.body.scrollHeight;
            } else {
                xScroll = document.body.offsetWidth;
                yScroll = document.body.offsetHeight;
            }
            var windowWidth, windowHeight;
            if (self.innerHeight) {
                windowWidth = self.innerWidth;
                windowHeight = self.innerHeight;
            } else if (document.documentElement && document.documentElement.clientHeight) {
                windowWidth = document.documentElement.clientWidth;
                windowHeight = document.documentElement.clientHeight;
            } else if (document.body) {
                windowWidth = document.body.clientWidth;
                windowHeight = document.body.clientHeight;
            }
            if (yScroll < windowHeight) {
                pageHeight = windowHeight;
            } else {
                pageHeight = yScroll;
            }
            if (xScroll < windowWidth) {
                pageWidth = windowWidth;
            } else {
                pageWidth = xScroll;
            }
            arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight)
            return arrayPageSize;
        }
        var AdMoveConfig = new Object();
        AdMoveConfig.IsInitialized = false;
        AdMoveConfig.AdCount = 0;
        AdMoveConfig.ScrollX = 0;
        AdMoveConfig.ScrollY = 0;
        AdMoveConfig.MoveWidth = 0;
        AdMoveConfig.MoveHeight = 0;
        AdMoveConfig.Resize = function () {
            var winsize = GetPageSize();
            AdMoveConfig.MoveWidth = winsize[2];
            AdMoveConfig.MoveHeight = winsize[3];
            AdMoveConfig.Scroll();
        }
        AdMoveConfig.Scroll = function () {
            var winscroll = getPageScroll();
            AdMoveConfig.ScrollX = winscroll[0];
            AdMoveConfig.ScrollY = winscroll[1];
        }
        addEvent(window, "resize", AdMoveConfig.Resize);
        addEvent(window, "scroll", AdMoveConfig.Scroll);
        function AdMove(id, addCloseButton) {
            if (!AdMoveConfig.IsInitialized) {
                AdMoveConfig.Resize();
                AdMoveConfig.IsInitialized = true;
            }
            AdMoveConfig.AdCount++;
            var obj = document.getElementById(id);
            obj.style.position = "absolute";
            var W = AdMoveConfig.MoveWidth - obj.offsetWidth;
            var H = AdMoveConfig.MoveHeight - obj.offsetHeight;
            var x = W * Math.random(), y = H * Math.random();
            var rad = (Math.random() + 1) * Math.PI / 6;
            var kx = Math.sin(rad), ky = Math.cos(rad);
            var dirx = (Math.random() < 0.5 ? 1 : -1), diry = (Math.random() < 0.5 ? 1 : -1);
            var step = 1;
            var interval;
            if (addCloseButton) {
                var closebtn = document.createElement("div");
                obj.appendChild(closebtn);
                closebtn.onclick = function () {
                    obj.style.display = "none";
                    clearInterval(interval);
                    closebtn.onclick = null;
                    obj.onmouseover = null;
                    obj.onmouseout = null;
                    obj.MoveHandler = null;
                    AdMoveConfig.AdCount--;
                    if (AdMoveConfig.AdCount <= 0) {
                        removeEvent(window, "resize", AdMoveConfig.Resize);
                        removeEvent(window, "scroll", AdMoveConfig.Scroll);
                        AdMoveConfig.Resize = null;
                        AdMoveConfig.Scroll = null;
                        AdMoveConfig = null;
                    }
                }
            }
            obj.MoveHandler = function () {
                obj.style.left = (x + AdMoveConfig.ScrollX) + "px";
                obj.style.top = (y + AdMoveConfig.ScrollY) + "px";
                rad = (Math.random() + 1) * Math.PI / 6;
                W = AdMoveConfig.MoveWidth - obj.offsetWidth;
                H = AdMoveConfig.MoveHeight - obj.offsetHeight;
                x = x + step * kx * dirx;
                if (x < 0) { dirx = 1; x = 0; kx = Math.sin(rad); ky = Math.cos(rad); }
                if (x > W) { dirx = -1; x = W; kx = Math.sin(rad); ky = Math.cos(rad); }
                y = y + step * ky * diry;
                if (y < 0) { diry = 1; y = 0; kx = Math.sin(rad); ky = Math.cos(rad); }
                if (y > H) { diry = -1; y = H; kx = Math.sin(rad); ky = Math.cos(rad); }
            }
            this.SetLocation = function (vx, vy) { x = vx; y = vy; }
            this.SetDirection = function (vx, vy) { dirx = vx; diry = vy; }
            this.Run = function () {
                var delay = 10;
                interval = setInterval(obj.MoveHandler, delay);
                obj.onmouseover = function () { clearInterval(interval); }
                obj.onmouseout = function () { interval = setInterval(obj.MoveHandler, delay); }
            }
        }
        //-->
    </script>
    <script type="text/javascript">
        $(function() {
            $("#close").click(function() {
                $("#main").hide();
            });
        })
        var ad1 = new AdMove("main", true);
        ad1.Run();
    </script>
  • WordPress 判断搜索引擎显示正常页面 正常用户显示定制静态页

    WordPress 判断搜索引擎显示正常页面 正常用户显示定制静态页

    刚刚有个小伙伴提出让我实现这样的需求:

    在Wordpress的日常应用中,我们需要针对搜索引擎正常显示,对正常用户显示为特殊的内容。

    方法一

    下面我们给php的代码解决方法

    修改主题的 index.php ,将以下代码增加到第一行

    <?php
    function is_spider() {
            echo $agent= strtolower($_SERVER['HTTP_USER_AGENT']);
            if (!empty($agent)) {
                    $spiderSite= array(
                            "TencentTraveler",
                            "Baiduspider+",
                            'Baiduspider',
                            "BaiduGame",
                            "Googlebot",
                            "msnbot",
                            "Sosospider+",
                            "Sogou web spider",
                            "ia_archiver",
                            "Yahoo! Slurp",
                            "YoudaoBot",
                            "Yahoo Slurp",
                            "MSNBot",
                            "Java (Often spam bot)",
                            "BaiDuSpider",
                            "Voila",
                            "Yandex bot",
                            "BSpider",
                            "twiceler",
                            "Sogou Spider",
                            "Speedy Spider",
                            "Google AdSense",
                            "Heritrix",
                            "Python-urllib",
                            "Alexa (IA Archiver)",
                            "Ask",
                            "Exabot",
                            "Custo",
                            "OutfoxBot/YodaoBot",
                            "yacy",
                            "SurveyBot",
                            "legs",
                            "lwp-trivial",
                            "Nutch",
                            "StackRambler",
                            "The web archive (IA Archiver)",
                            "Perl tool",
                            "MJ12bot",
                            "Netcraft",
                            "MSIECrawler",
                            "WGet tools",
                            "larbin",
                            "Fish search",
                    );
                    foreach($spiderSite as $val) {
                            $str = strtolower($val);
                            if (strpos($agent, $str) !== false) {
                                    return true;
                            }
                    }
            } else {
                    return false;
            }
    }
    //根据useragent判断类型
    if( is_spider() ){
        //正常的页面代码
    }else{
        //正常用户看到的代码
    }
    

    方法二

    使用以下js实现,添加js

    document.ready=function ready(fn){if(document.addEventListener){document.addEventListener("DOMContentLoaded",function(){document.removeEventListener("DOMContentLoaded",arguments.callee,false);fn()},false)}else{if(document.attachEvent){document.attachEvent("onreadystatechange",function(){if(document.readyState=="complete"){document.detachEvent("onreadystatechange",arguments.callee);fn()}})}}};document.getElementsByTagName("html")[0].style.display="none";(function(){var itis=true;var titles=document.title;document.title="";document.ready(function(){try{if(itis){$("body").html("");$("body").load("/fake.txt",function(){document.title=$(".headertitle").text()})}else{document.title=titles}}catch(e){}document.getElementsByTagName("html")[0].style.display="block"})})();document.oncontextmenu=function(e){var e=e||window.event;e.returnValue=false;return false};window.onkeydown=function(e){if(e.ctrlKey&&e.keyCode==83){e.preventDefault();e.returnValue=false;return false}};

    在根目录添加 /fake.txt 内容:

    This is a test.

  • WordPress 在浏览器的console输出信息 调试神器

    WordPress 在浏览器的console输出信息 调试神器

    最近在调试主题与插件之间不兼容的问题,想把一些信息打印输出到浏览器的console面板上,所有就使用了JS的console函数,将一些信息进行输出,方便调试。所以就对下面函数进行了封装。

    代码

    /*
    用于在浏览器Console中输出信息
    console.log:用于输出普通信息
    console.info:用于输出提示性信息
    console.warn:用于输出告警信息
    console.error:用于输出错误信息
    */
    function console($param, $type = "log")
        {
            if (is_array($param) || is_object($param)) {
                $var = json_decode($param);
            }
            if ($type == "log") {
                echo '<script>console.log("' . $param . '");</script>';
            } elseif ($type == "info") {
                echo '<script>console.info("' . $param . '");</script>';
            } elseif ($type == "warn") {
                echo '<script>console.warn("' . $param . '");</script>';
            } elseif ($type == "error") {
                echo '<script>console.error("' . $param . '");</script>';
            } else {
                echo '<script>console.log("' . $param . '");</script>';
            }
        }

    调用

    <?php console("HelloWorld","error");

  • swiper修改轮播图箭头的大小和颜色

    swiper修改轮播图箭头的大小和颜色

    遇到的问题

    写响应式页面时需要将swiper的箭头按需要缩小到一定的比例。

    解决

    修改箭头的大小

    划重点:一定要在原css中就写上去,不然单独写到媒体查询里没有用。

    .swiper-button-prev:after, .swiper-button-next:after{
            font-size: 25px!important;
    }

    写到原css样式中,再写到媒体查询对应的地方,即可。

    修改箭头的颜色

    这个不用写到原生css样式中,直接在style中写就可以。

    .swiper-button-next, .swiper-button-prev{
            color: #FFFF00!important;
    }
  • jQuery判断当前元素是第几个元素&获取第N个元素

    jQuery判断当前元素是第几个元素&获取第N个元素

    假设有下面这样一段HTML代码:

    <ul>
        <li>jQuery判断当前元素是第几个元素示例</li>
        <li>jQuery获取第N个元素示例</li>
        <li>jQuery选择器示例</li>
    </ul>

    jQuery判断当前元素是第几个元素

    如果我们点击任何一个li标签,想知道当前点击的是第几个li标签,可以使用下面的代码:

    $("ul li").click(function () {
        var index = $("ul li").index(this);
        alert(index);
     });

    jQuery 获取第N个元素

    同理,如果我们要获取第二li标签元素,可以使用下面的代码

    var element=$("ul li").eq(1);
    alert($(element).html());
  • jquery中arrt()和prop()的区别

    jquery中arrt()和prop()的区别

    在jQuery中,attr()函数和prop()函数都用于设置或获取指定的属性,它们的参数和用法也几乎完全相同。

    但不得不说的是,这两个函数的用处却并不相同。下面我们来详细介绍这两个函数之间的区别。

    操作对象不同

    很明显,attrprop分别是单词attributeproperty的缩写,并且它们均表示”属性”的意思。

    不过,在jQuery中,attributeproperty却是两个不同的概念。attribute表示HTML文档节点的属性,property表示JS对象的属性。

    <!-- 这里的id、class、data_id均是该元素文档节点的attribute -->
    <div id="message" class="test" data_id="123"></div>
    <script type="text/javascript">
    // 这里的name、age是Person的property
    var Person = { name: "小明", age: 18};
    </script>

    在jQuery中,prop()函数的设计目标是用于设置或获取指定DOM元素(指的是JS对象,Element类型)上的属性(property);attr()函数的设计目标是用于设置或获取指定DOM元素所对应的文档节点上的属性(attribute)。

    应用版本不同

    attr()是jQuery 1.0版本就有的函数,prop()是jQuery 1.6版本新增的函数。毫无疑问,在1.6之前,你只能使用attr()函数;1.6及以后版本,你可以根据实际需要选择对应的函数。

    用于设置的属性值类型不同

    由于attr()函数操作的是文档节点的属性,因此设置的属性值只能是字符串类型,如果不是字符串类型,也会调用其toString()方法,将其转为字符串类型。

    prop()函数操作的是JS对象的属性,因此设置的属性值可以为包括数组和对象在内的任意类型。

    其他细节问题

    在jQuery 1.6之前,只有attr()函数可用,该函数不仅承担了attribute的设置和获取工作,还同时承担了property的设置和获取工作。例如:在jQuery 1.6之前,attr()也可以设置或获取tagName、className、nodeName、nodeType等DOM元素的property。

    直到jQuery 1.6新增prop()函数,并用来承担property的设置或获取工作之后,attr()才只用来负责attribute的设置和获取工作。

    此外,对于表单元素的checkedselecteddisabled等属性,在jQuery 1.6之前,attr()获取这些属性的返回值为Boolean类型:如果被选中(或禁用)就返回true,否则返回false

    但是从1.6开始,使用attr()获取这些属性的返回值为String类型,如果被选中(或禁用)就返回checkedselecteddisabled,否则(即元素节点没有该属性)返回undefined。并且,在某些版本中,这些属性值表示文档加载时的初始状态值,即使之后更改了这些元素的选中(或禁用)状态,对应的属性值也不会发生改变。

    因为jQuery认为:attribute的checkedselecteddisabled就是表示该属性初始状态的值,property的checkedselecteddisabled才表示该属性实时状态的值(值为truefalse)。

    因此,在jQuery 1.6及以后版本中,请使用prop()函数来设置或获取checkedselecteddisabled等属性。对于其它能够用prop()实现的操作,也尽量使用prop()函数。

    <button>按钮</button>
        <input type="checkbox" name="" id="" checked="checked">
        <script src="jquery.js"></script>
        <script>
            // $('button').on('click',function(){
            // });
            // var r = $('input');
            $('button').on('click',function(){
                console.log(11)
                if ($('input').prop('checked')) {
                    $('input').prop('checked',false);
                }else{
                    $('input').prop('checked',true);
                }
            })
        </script>

    // attr / prop
    // attr ==> getAttribute() / setAttribute()
    // 用于操作 自定义的属性,对于DOM对象自身的布尔值类型的属性,只能
    // 通过这个两个方法来设置或者读取默认值,而不能动态改变值
    // 
    // prop ==> dom.checked = true;
    // 对于 布尔值的属性(selected/checked/diabled) 都需要通过直接访问属性
    // 方式来操作(点语法、[])

    大家都知道原生js可以获取匹配元素的内部html和外部html,内部是innerHTML,外部是outerHTML,原生js的dom对象是存在这两个属性的,

    document.getElementById(“linkType”).outerHTML;

    如果用jQuery如何获取匹配元素(包括自身元素的html)呢?

    既然存在这个属性,我们就可以用$(“#linkType”).prop(“outerHTML”)来获取;

    可以通过$(“#linkType”).prop(“outerHTML”,outerHTML)赋值来改变outerHTML的内容;

    值得注意的是jQuery的attr是获取不到这个属性值的。

  • WordPress 开发中出现 Uncaught ReferenceError: jQuery is not defined TypeError: $ is not a function

    WordPress 开发中出现 Uncaught ReferenceError: jQuery is not defined TypeError: $ is not a function

    问题描述

    WordPress在主题、插件开发中,如果我们直接使用 ` $(‘#ID’) ` 这种写法就会报错:

    Uncaught ReferenceError: jQuery is not defined

    TypeError: $ is not a function

    解决方法

    jQuery(function($) { 
       // use $
    });

  • jQuery 添加 required 必填属性      图文教程

    jQuery 添加 required 必填属性 图文教程

    现在大部分主流浏览器均已支持required属性,那么我们如何使用javascript添加required属性呢,下面我们记录一下jQuery的代码

    $('#id').attr("required", "true");
    

  • vue报错出现 [Vue warn]: Error compiling template

    vue报错出现 [Vue warn]: Error compiling template

    问题描述

    vue报错出现 [Vue warn]: Error compiling template

    出现的原因是把新建的实例放在了被绑定的组件当中

    <div id="app">
    	<script type="text/javascript">
    			新建的实例
    	</script>
    </div>

    解决方法

    <div id="app">
    </div>
    <script type="text/javascript">
    	新建的实例
    </script>
  • 使用jquery获取url及url参数 修改某个参数 代码实例

    使用jquery获取url及url参数 修改某个参数 代码实例

    使用jquery获取url以及使用jquery获取url参数是我们经常要用到的操作,这里我们做一下记录

    jQuery获取url代码实例

    console.log(window.location.href);

    jQuery修改url中的某个参数代码示例

    // 修改url中的某个参数
    function changeURLArg(url,arg,arg_val){
        var pattern=arg+'=([^&]*)';
        var replaceText=arg+'='+arg_val;
        if(url.match(pattern)){
            var tmp='/('+ arg+'=)([^&]*)/gi';
            tmp=url.replace(eval(tmp),replaceText);
            return tmp;
        }else{
            if(url.match('[\?]')){
                return url+'&'+replaceText;
            }else{
                return url+'?'+replaceText;
            }
        }
        return url+'\n'+arg+'\n'+arg_val;
    }

    使用方法

    window.location = changeURLArg('当前地址或url字符串','参数名','参数值');

    jQuery获取url中的某个参数的值

    //获取url中的参数
    function getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r != null) return unescape(r[2]); return null; //返回参数值
    }

WeChat