网站建设

wordpress博客不刷新自动换背景图片php代码

很多wordpress博客有几个背景,不过需要刷新才能切换,运用的方法是用php随机输出,如果你们需要,也可以拿去用。
将下列代码添加到functions.php里面
function BYMT_rand_bg () {
$randbg = mt_rand(1, 8); /*背景图片随机数*/
$randbgurl = get_bloginfo(‘template_directory’).’/images/background/background’.$randbg.’.jpg’; /*背景图片地址*/
echo'<style>body{background: url(‘.$randbgurl.’) no-repeat top center;background-attachment:fixed;}</style>’.”n”;
}
add_action(‘wp_head’, ‘BYMT_rand_bg’, 100);
下面我介绍一个无刷新自动切换背景的方法,运用的是jQuery的setInterval。
将下列代码添加到主题jQ文件里,或者直接用<script type=”text/javascript”></script>包上放在页脚代码里。
//背景自动切换
jQuery(document).ready(function(){
setInterval(function() {
var imgpath = ‘../wp-content/themes/BYMT/images/background/’; /*背景图片目录*/
var imgrand = Math.floor(Math.random() * 8 + 1); /*背景图片随机数*/
var randurl = ‘<style>body{background: url(‘ + imgpath +’background’+ imgrand + ‘.jpg) no-repeat top center;background-attachment:fixed;}</style>’;
$(“#randbg”).html(randurl);
},10000); /*自动切换时间(毫秒)*/
});
接着在主题<body>后面添加上:
<div id=”randbg”></div>
OK,代码就是这样。

Related Articles

发表回复

Back to top button