在Materialize设计中删除转盘图像的不透明度

Remove opacity from carousel images in Materialize design

本文关键字:图像 不透明度 删除 Materialize      更新时间:2023-09-26

我使用的是3d旋转木马。图像也有一些不透明度。但我不希望图像不透明。

    $('.carousel').carousel({
            dist:0,
            shift:0,
            padding:20, 
           interval:100
      });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/css/materialize.min.css" rel="stylesheet" type="text/css">
   
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/js/materialize.min.js"></script>
 <div class="carousel">
    <a class="carousel-item" href="#one!"><img src="http://lorempixel.com/250/250/nature/1"></a>
    <a class="carousel-item" href="#two!"><img src="http://lorempixel.com/250/250/nature/2"></a>
    <a class="carousel-item" href="#three!"><img src="http://lorempixel.com/250/250/nature/3"></a>
    <a class="carousel-item" href="#four!"><img src="http://lorempixel.com/250/250/nature/4"></a>
    <a class="carousel-item" href="#five!"><img src="http://lorempixel.com/250/250/nature/5"></a>
</div>

我想减少所有图像的不透明度。

旋转木马插件没有设置图像不透明度的选项,因此必须通过css样式实现。不是最好的选择,但我看不到任何更简单的方法:)

$('.carousel').carousel({
  dist: 0,
  shift: 0,
  padding: 20,
  interval: 100
});
.carousel .carousel-item {
  opacity: 1 !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/css/materialize.min.css" rel="stylesheet" type="text/css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/js/materialize.min.js"></script>
<div class="carousel">
  <a class="carousel-item" href="#one!">
    <img src="http://lorempixel.com/250/250/nature/1">
  </a>
  <a class="carousel-item" href="#two!">
    <img src="http://lorempixel.com/250/250/nature/2">
  </a>
  <a class="carousel-item" href="#three!">
    <img src="http://lorempixel.com/250/250/nature/3">
  </a>
  <a class="carousel-item" href="#four!">
    <img src="http://lorempixel.com/250/250/nature/4">
  </a>
  <a class="carousel-item" href="#five!">
    <img src="http://lorempixel.com/250/250/nature/5">
  </a>
</div>

第一个答案,使其成为:

.carousel .carousel-item {
  opacity: 1 !important;
} 

对我来说不起作用,因为我有一个要求,在旋转木马上显示3张没有任何不透明的图像。

第二个答案,很难理解和进一步调整。

我的解决方案:使用MutationObserver,监听/观察.carousel父分区的属性变化。

$(document).ready(function () {
    $('.carousel').carousel({
        'numVisible': 3
    });
    var targetNode = document.querySelectorAll(".carousel")[0];
    // Options for the observer (which mutations to observe)
    var config = { attributes: true, childList: true, subtree: true };
    // Callback function to execute when mutations are observed
    var callback = function(mutationsList, observer) {
        // Use traditional 'for loops' for IE 11
        for(let mutation of mutationsList) {
            if (mutation.type === 'childList') {
                console.log('A child node has been added or removed.');
            }
            else if (mutation.type === 'attributes') {
                console.log('The ' + mutation.attributeName + ' attribute was modified.');
            }
            displayTopThreeImages();
        }
    };
    // Create an observer instance linked to the callback function
    var observer = new MutationObserver(callback);
    // Start observing the target node for configured mutations
    observer.observe(targetNode, config);
    function displayTopThreeImages() {
        [...document.querySelectorAll(".carousel-item")].forEach(item=>{item.style.opacity = item.style.opacity > 0 ? 1 : item.style.opacity});
    }
})

上面的解决方案删除了所有不透明度转换,包括左侧最后一项和右侧最后一项的转换。我不喜欢它的外观,所以我浏览了Materialize Carousel的代码,最后提出了这个使用原型更改_scroll函数的解决方案,希望这能帮助到别人,只需在初始化Carousel之前放置这个代码:

M.Carousel.prototype._scroll = function(x) {
// Track scrolling state
if (!this.$el.hasClass('scrolling')) {
    this.el.classList.add('scrolling');
}
if (this.scrollingTimeout != null) {
    window.clearTimeout(this.scrollingTimeout);
}
this.scrollingTimeout = window.setTimeout(() => {
    this.$el.removeClass('scrolling');
}, this.options.duration);
// Start actual scroll
let i,
    half,
    delta,
    dir,
    tween,
    el,
    elLastLeft,
    elLastRight,
    alignment,
    zTranslation,
    tweenedOpacity,
    centerTweenedOpacity;
let lastCenter = this.center;
let numVisibleOffset = 1 / this.options.numVisible;
this.offset = typeof x === 'number' ? x : this.offset;
this.center = Math.floor((this.offset + this.dim / 2) / this.dim);
delta = this.offset - this.center * this.dim;
dir = delta < 0 ? 1 : -1;
tween = -dir * delta * 2 / this.dim;
half = this.count >> 1;
if (this.options.fullWidth) {
    alignment = 'translateX(0)';
    centerTweenedOpacity = 1;
} else {
    alignment = 'translateX(' + (this.el.clientWidth - this.itemWidth) / 2 + 'px) ';
    alignment += 'translateY(' + (this.el.clientHeight - this.itemHeight) / 2 + 'px)';
    centerTweenedOpacity = 1 - numVisibleOffset * tween;
}
// Set indicator active
if (this.showIndicators) {
    let diff = this.center % this.count;
    let activeIndicator = this.$indicators.find('.indicator-item.active');
    if (activeIndicator.index() !== diff) {
      activeIndicator.removeClass('active');
      this.$indicators
        .find('.indicator-item')
        .eq(diff)[0]
        .classList.add('active');
    }
}
// center
// Don't show wrapped items.
if (!this.noWrap || (this.center >= 0 && this.center < this.count)) {
    el = this.images[this._wrap(this.center)];
    elLastLeft = this.images[this._wrap(this.center - half)];
    elLastRight = this.images[this._wrap(this.center + half)];
    // Add active class to center item.
    if (!$(el).hasClass('active')) {
      this.$el.find('.carousel-item').removeClass('active');
      el.classList.add('active');
    }
    let transformString = `${alignment} translateX(${-delta / 2}px) translateX(${dir *
      this.options.shift *
      tween *
      i}px) translateZ(${this.options.dist * tween}px)`;
    this._updateItemStyle(el, centerTweenedOpacity, 0, transformString);
}
for (i = 1; i <= half; ++i) {
    // right side
    if (this.options.fullWidth) {
      zTranslation = this.options.dist;
      tweenedOpacity = i === half && delta < 0 ? 1 - tween : 1;
    } else {
      zTranslation = this.options.dist * (i * 2 + tween * dir);
      // Amend the tweenedOpacity
      tweenedOpacity = (1 * (1 * 2 + tween * -dir )) -1;
      tweenedOpacity = parseFloat(tweenedOpacity.toFixed(2));
    }
    // Don't show wrapped items.
    if (!this.noWrap || this.center + i < this.count) {
        el = this.images[this._wrap(this.center + i)];
        let transformString = `${alignment} translateX(${this.options.shift +
            (this.dim * i - delta) / 2}px) translateZ(${zTranslation}px)`;
        // Only give Opacity Transition to last item 
        if (i == half ) {
            this._updateItemStyle(el, tweenedOpacity, -i, transformString);
        }
        else {
            this._updateItemStyle(el, centerTweenedOpacity, -i, transformString);
        }
    }
    // left side
    if (this.options.fullWidth) {
      zTranslation = this.options.dist;
      tweenedOpacity = i === half && delta > 0 ? 1 - tween : 1;
    } else {
      zTranslation = this.options.dist * (i * 2 - tween * dir);
      // Amend the tweenedOpacity
      tweenedOpacity = (1 * (1 * 2 - tween * -dir )) -1;
      tweenedOpacity = parseFloat(tweenedOpacity.toFixed(2));           
    }
    // Don't show wrapped items.
    if (!this.noWrap || this.center - i >= 0) {
        el = this.images[this._wrap(this.center - i)];
        let transformString = `${alignment} translateX(${-this.options.shift +
            (-this.dim * i - delta) / 2}px) translateZ(${zTranslation}px)`;
        // Only give Opacity Transition to last item
        if (i == half ) {    
            this._updateItemStyle(el, tweenedOpacity, -i, transformString);
        }
        else {
            this._updateItemStyle(el, centerTweenedOpacity, -i, transformString);
        }
    }
}
// center
// Don't show wrapped items.
if (!this.noWrap || (this.center >= 0 && this.center < this.count)) {
    el = this.images[this._wrap(this.center)];
    let transformString = `${alignment} translateX(${-delta / 2}px) translateX(${dir *
      this.options.shift *
      tween}px) translateZ(${this.options.dist * tween}px)`;
    this._updateItemStyle(el, centerTweenedOpacity, 0, transformString);
}
// onCycleTo callback
let $currItem = this.$el.find('.carousel-item').eq(this._wrap(this.center));
if (lastCenter !== this.center && typeof this.options.onCycleTo === 'function') {
    this.options.onCycleTo.call(this, $currItem[0], this.dragged);
}
// One time callback
if (typeof this.oneTimeCallback === 'function') {
    this.oneTimeCallback.call(this, $currItem[0], this.dragged);
    this.oneTimeCallback = null;
}
};
// Here you init the carousel ...