在WordPress上使用Kenb(Ken Burns)滑块 - 如何使幻灯片以随机顺序加载



我在WordPress上使用Kenb效果滑块。我希望幻灯片以随机顺序加载。这可能吗?

我认为这是下面的相关js。您还可以在以下位置查看该网站: http://goo.gl/yBGZAk

(function($){
$.fn.kenburns = function(options) {
    var $canvas = $(this);
    var ctx = this[0].getContext('2d');
    var start_time = null;
    var width = $canvas.width();
    var height = $canvas.height();  
    var image_paths = options.images;       
    var display_time = options.display_time || 7000;
    var fade_time = Math.min(display_time / 2, options.fade_time || 1000);
    var solid_time = display_time - (fade_time * 2);
    var fade_ratio = fade_time - display_time
    var frames_per_second = options.frames_per_second || 30;        
    var frame_time = (1 / frames_per_second) * 1000;
    var zoom_level = 1 / (options.zoom || 2);
    var clear_color = options.background_color || '#000000';    
    var images = [];
    $(image_paths).each(function(i, image_path){
        images.push({path:image_path,
                     initialized:false,
                     loaded:false});
    });     
    function get_time() {
        var d = new Date();
        return d.getTime() - start_time;
    }

这是在主题的功能.php文件中:

function kenres() {
        jQuery('#kenburns').kenburns({
            //Functionality
                images: [
                <?php   $tti = 0; while (have_posts()): the_post(); ?>
                    <?php if ($tti)
                        echo ',';
                    $tti++;
                    $full = wp_get_attachment_image_src(get_post_thumbnail_id(), 'full');
                    $title = get_post_meta(get_the_ID(), '_slide_title_value', true);
                    echo "'";
                    echo $full[0];
                    echo "'" ?>                  
                     <?php endwhile ?>
                     <?php wp_reset_query(); ?>

初始化滑块时,将图像数组(称为images)作为选项传递,因此,如果随机化该列表,您将具有不同的顺序。

您可以通过PHP执行此操作(当您输出脚本代码并传递图像数组时),shuffle()

$images = array('image1.jpg', 'image2.jpg', 'image3.jpg');
shuffle( $images );

或者如果你想在Javascript代码中做到这一点,你可以使用这种方法:

['image1.jpg', 'image2.jpg', 'image3.jpg'].sort(function() { return 0.5 - Math.random() });

请参阅以下示例:

var random = [
  
  'image1.jpg',
  'image2.jpg',
  'image3.jpg',
  'image4.jpg',
  'image5.jpg',
].sort(function() { return 0.5 - Math.random() });
document.getElementById('output').innerHTML = random;
<div id="output"></div>

更新

看到更新后的问题中的新代码,您可以将 PHP 部分(images = [ 之后的所有内容)替换为以下内容:

<?php
$images = array();
while (have_posts()): the_post();
    $full = wp_get_attachment_image_src(get_post_thumbnail_id(), 'full');
    $title = get_post_meta(get_the_ID(), '_slide_title_value', true);
    $images []= "'{$full[0]}'";
endwhile;
wp_reset_query();
shuffle($images);
echo implode(',', $images);
?>

基本上,此代码不是在每次迭代时回显图像路径,而是将路径添加到$images数组,然后在回显之前对其进行洗牌。

最新更新