首先需要下载Shake.js,shake.js github地址,我们只需要里面的shake.js,然后引入。
添加“摇一摇”事件监听:
1 2 3 4 5 6 7 8 9 10 |
window.addEventListener('shake', shakeEventDidOccur, false); //function to call when shake occurs function shakeEventDidOccur () { //put your own code here etc. if (confirm("Undo?")) { } } |
取消监听:
1 |
window.removeEventListener('shake', shakeEventDidOccur, false); |
摇一摇随机文章实现方式:
JS代码,当然在这之前需要下载并安装咱们刚才说的shake.js脚本:
1 2 3 4 5 6 7 8 9 10 11 |
window.addEventListener('shake', shakeEventDidOccur, false); //function to call when shake occurs function shakeEventDidOccur () { jQuery.post(Bigfa.ajaxurl, { action : 'random_post', }, function(data) { window.location.href = data; }); } |
下面的代码扔到functions.php
中,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
wp_enqueue_script( 'key', true); wp_localize_script('key', 'Bigfa', array( "ajaxurl" => admin_url('admin-ajax.php') )); add_action( 'wp_ajax_random_post', 'bigfa_random_post' ); add_action( 'wp_ajax_nopriv_random_post', 'bigfa_random_post' ); function bigfa_random_post() { $posts = get_posts('post_type=post&orderby=rand&numberposts=1'); foreach($posts as $post) { $link = get_permalink($post); } echo $link; exit; } |
完全代码布署。
浏览器和设备支持情况
iOS Safari 4.2.1 (and above)
Android 4.0.3 (default browser)
Opera Mobile (Android)
BlackBerry PlayBook 2.0
Firefox for Android
FirefoxOS Devices