我正在尝试使用“彩色小偷”使用图像的主色为div
s添加背景色。我已经能够使它适用于集合中的最后一张图像,但无法将其应用于每个图像。我正在使用ACF的repeater字段来生成图像,并为每个图像的容器创建了唯一的ID。我不确定如何使着色应用于集合中的每个图像。
PHP:
<div class="parallax-gallery">
<?php if( have_rows('parallax_gallery') ): ?>
<?php while( have_rows('parallax_gallery') ): the_row();
$parallaxGalleryImage = get_sub_field('parallax_gallery_image');
$parallaxGalleryText = get_sub_field('parallax_gallery_text');
$parallaxGalleryLink = get_sub_field('parallax_gallery_link');
?>
<?php $id = uniqid(); ?>
<div id="parallax-gallery-content-<?php echo $id; ?>">
<?php if( $parallaxGalleryImage ): ?>
<a href="<?php echo esc_url($parallaxGalleryLink) ?>"><img src="<?php echo esc_url($parallaxGalleryImage['url']); ?>" alt="<?php echo esc_html($parallaxGalleryImage['alt']); ?>" /></a>
<?php endif; ?>
<?php if( $parallaxGalleryText ): ?>
<p class="parallax-gallery-text"><?php echo wp_kses_post($parallaxGalleryText) ?></p>
<?php endif; ?>
</div>
<?php endwhile; ?>
<?php endif; ?>
JS:
var img = document.createElement("img");
img.src = "<?php echo esc_url($parallaxGalleryImage['url']); ?>";
img.onload = function () {
var colorThief = new ColorThief();
var color = colorThief.getColor(img);
$("#parallax-gallery-content-<?php echo $id; ?>").css("background-color", "rgb(" + color + ")");
};
我也尝试过使用parallax-gallery-content
一类(没有uniqid)并使用循环,但是随后它将最后一张图像的颜色应用于所有图像背景
JS:
var img = new Image;
img.src = "<?php echo esc_url($parallaxGalleryImage['url']); ?>";
img.onload = function () {
var colorThief = new ColorThief();
var color = colorThief.getColor(img);
$('.parallax-gallery-content img').each(function() {
$(this).closest('.parallax-gallery-content').css("backgroundColor", "rgb(" + color + ")");
});
}
任何帮助将不胜感激!