programing

jQuery slideUp and slideDown에 해당하는 CSS3?

lastmoon 2023. 9. 9. 10:05
반응형

jQuery slideUp and slideDown에 해당하는 CSS3?

jQuery의 슬라이드 Down and slide Up으로 애플리케이션 성능이 떨어집니다.나는 그것을 지원하는 브라우저에서 CSS3와 동등한 것을 사용하려고 합니다.

하여 CSS3 을 과 를 하는 이 합니까 하여 합니까 이 을 를 하여 과 display: none;display: block;물건을 아래로 밀거나 위로 밀면서?

당신은 다음과 같은 것을 할 수 있습니다.

#youritem .fade.in {
    animation-name: fadeIn;
}

#youritem .fade.out {
    animation-name: fadeOut;
}

@keyframes fadeIn {
    0% {
        opacity: 0;
        transform: translateY(startYposition);
    } 
    100% {
        opacity: 1;
        transform: translateY(endYposition);
    }
}

@keyframes fadeOut {
    0% {
        opacity: 1;
        transform: translateY(startYposition);
    } 
    100% {
        opacity: 0;
        transform: translateY(endYposition);
    }
}

예제 - 슬라이드 및 페이드:

용기의 높이가 아니라 상단/좌표에 따라 불투명도를 슬라이드하고 애니메이션화합니다.보기 예제

예제 - 자동 높이/Javascript 없음:여기 자동 높이와 자바스크립트가 없는 키가 필요 없는 실시간 샘플이 있습니다.
보기 예제

솔루션을 변경하여 모든 최신 브라우저에서 작동하도록 했습니다.

CSS 스니펫:

-webkit-transition: height 1s ease-in-out;
-moz-transition: height 1s ease-in-out;
-ms-transition: height 1s ease-in-out;
-o-transition: height 1s ease-in-out;
transition: height 1s ease-in-out;

js 조각:

    var clone = $('#this').clone()
                .css({'position':'absolute','visibility':'hidden','height':'auto'})
                .addClass('slideClone')
                .appendTo('body');

    var newHeight = $(".slideClone").height();
    $(".slideClone").remove();
    $('#this').css('height',newHeight + 'px');

다음은 http://jsfiddle.net/RHPQd/ 의 전체 예시입니다.

주로 애니메이션을 만들 키를 알아야 하기 때문에 키 전환 작업이 다소 까다로울 수 있습니다.이 문제는 애니메이션화할 요소에 패딩을 입혀 더욱 복잡해집니다.

제가 생각해낸 것은 다음과 같습니다.

다음과 같은 스타일을 사용합니다.

    .slideup, .slidedown {
        max-height: 0;            
        overflow-y: hidden;
        -webkit-transition: max-height 0.8s ease-in-out;
        -moz-transition: max-height 0.8s ease-in-out;
        -o-transition: max-height 0.8s ease-in-out;
        transition: max-height 0.8s ease-in-out;
    }
    .slidedown {            
        max-height: 60px ;  // fixed width                  
    }

내용물을 다른 용기에 싸서 미끄러지는 용기에 패딩/마진/경계가 없도록 합니다.

  <div id="Slider" class="slideup">
    <!-- content has to be wrapped so that the padding and
            margins don't effect the transition's height -->
    <div id="Actual">
            Hello World Text
        </div>
  </div>

그런 다음 스크립트(또는 바인딩 프레임워크의 선언 마크업)를 사용하여 CSS 클래스를 트리거합니다.

  $("#Trigger").click(function () {
    $("#Slider").toggleClass("slidedown slideup");
  });

예: http://plnkr.co/edit/uhChl94nLhrWCYVhRBUF?p=preview

이것은 고정된 크기의 컨텐츠에 대해서도 잘 작동합니다.보다 일반적인 솔루션의 경우 코드를 사용하여 전환이 활성화될 때 요소의 크기를 파악할 수 있습니다.다음은 바로 다음을 수행하는 jQuery 플러그인입니다.

$.fn.slideUpTransition = function() {
    return this.each(function() {
        var $el = $(this);
        $el.css("max-height", "0");
        $el.addClass("height-transition-hidden");
    });
};

$.fn.slideDownTransition = function() {
    return this.each(function() {
        var $el = $(this);
        $el.removeClass("height-transition-hidden");

        // temporarily make visible to get the size
        $el.css("max-height", "none");
        var height = $el.outerHeight();

        // reset to 0 then animate with small delay
        $el.css("max-height", "0");

        setTimeout(function() {
            $el.css({
                "max-height": height
            });
        }, 1);
    });
};

다음과 같이 트리거될 수 있습니다.

$("#트리거").클릭(함수) {

    if ($("#SlideWrapper").hasClass("height-transition-hidden"))
        $("#SlideWrapper").slideDownTransition();
    else
        $("#SlideWrapper").slideUpTransition();
});

마크업에 반대합니다.

<style>
#Actual {
    background: silver;
    color: White;
    padding: 20px;
}

.height-transition {
    -webkit-transition: max-height 0.5s ease-in-out;
    -moz-transition: max-height 0.5s ease-in-out;
    -o-transition: max-height 0.5s ease-in-out;
    transition: max-height 0.5s ease-in-out;
    overflow-y: hidden;            
}
.height-transition-hidden {            
    max-height: 0;            
}
</style>
<div id="SlideWrapper" class="height-transition height-transition-hidden">
    <!-- content has to be wrapped so that the padding and
        margins don't effect the transition's height -->
    <div id="Actual">
     Your actual content to slide down goes here.
    </div>
</div>

예: http://plnkr.co/edit/Wpcgjs3FS4ryrhQUAOcU?p=preview

좀 더 자세한 내용을 알고 싶으시다면 최근 블로그에 글을 올렸습니다.

http://weblog.west-wind.com/posts/2014/Feb/22/Using-CSS-Transitions-to-SlideUp-and-SlideDown

그래서 저는 제 질문에 답했습니다 :)

@True의 대답은 어떤 요소를 특정한 높이로 변화시키는 것을 고려했습니다.이것의 문제는 제가 요소의 높이를 모른다는 것입니다. (요소가 요동칠 수 있습니다.

저는 max-height를 전환으로 사용하는 다른 솔루션을 찾았지만, 이것은 저에게 매우 육중한 애니메이션을 만들어 주었습니다.

아래의 제 솔루션은 웹킷 브라우저에서만 작동합니다.

순수하게 CSS는 아니지만, 일부 JS에 의해 결정되는 높이 전환을 포함합니다.

$('#click-me').click(function() {
  var height = $("#this").height();
  if (height > 0) {
    $('#this').css('height', '0');
  } else {
    $("#this").css({
      'position': 'absolute',
      'visibility': 'hidden',
      'height': 'auto'
    });
    var newHeight = $("#this").height();
    $("#this").css({
      'position': 'static',
      'visibility': 'visible',
      'height': '0'
    });
    $('#this').css('height', newHeight + 'px');
  }
});
#this {
  width: 500px;
  height: 0;
  max-height: 9999px;
  overflow: hidden;
  background: #BBBBBB;
  -webkit-transition: height 1s ease-in-out;
}

#click-me {
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>

<p id="click-me">click me</p>
<div id="this">here<br />is<br />a<br />bunch<br />of<br />content<br />sdf</div>
<div>always shows</div>

JSFiddle 보기

현대 브라우저 CSS 전환을 활용하지 않고 더 많은 CSS와 더 적은 jquery를 사용하여 더 단순하고 빠르게 작업을 수행하는 이유는 무엇입니까?

여기 위 아래로 미끄러지는 코드가 있습니다.

여기 왼쪽에서 오른쪽으로 미끄러지는 코드가 있습니다.

마찬가지로 변환 원점과 변환: 스케일X(0) 또는 변환: 스케일Y(0)를 적절히 변경하여 슬라이딩을 위에서 아래로 또는 오른쪽에서 왼쪽으로 변경할 수 있습니다.

대부분의 사람들이 하드웨어 가속을 지원하기 때문에 모바일 장치에서 잘 작동하는 CSS3 변환 속성을 사용하는 jQuery Transit Plugin을 사용하는 것을 추천합니다.

JS Fiddle 예제

HTML:

<div class="moveMe">
    <button class="moveUp">Move Me Up</button>
    <button class="moveDown">Move Me Down</button>
    <button class="setUp">Set Me Up</button>
    <button class="setDown">Set Me Down</button>
 </div>

자바스크립트:

$(".moveUp").on("click", function() {
    $(".moveMe").transition({ y: '-=5' });
});

$(".moveDown").on("click", function() {
    $(".moveMe").transition({ y: '+=5' });
});

$(".setUp").on("click", function() {
    $(".moveMe").transition({ y: '0px' });
});

$(".setDown").on("click", function() {
    $(".moveMe").transition({ y: '200px' });
});

네, 조사하고 실험한 결과 최고의 접근법은 키를 높이는 것이라고 생각합니다.0px, 정확한 높이로 옮겨가게 해주세요자바스크립트로 정확한 키를 얻을 수 있습니다.자바스크립트는 애니메이션을 하는 것이 아니라 높이 값을 바꾸는 것입니다.확인:

function setInfoHeight() {
  $(window).on('load resize', function() {
    $('.info').each(function () {
      var current = $(this);
      var closed = $(this).height() == 0;
      current.show().height('auto').attr('h', current.height() );
      current.height(closed ? '0' : current.height());
    });
  });

페이지가 로드되거나 크기가 조정될 때마다 클래스가 있는 요소info그것을 얻을 것입니다.h속성이 업데이트되었습니다.그러면 당신은 버튼을 통해style="height: __"이전에 설정했던 대로h가치.

function moreInformation() {
  $('.icon-container').click(function() {
    var info = $(this).closest('.dish-header').next('.info'); // Just the one info
    var icon = $(this).children('.info-btn'); // Select the logo

    // Stop any ongoing animation loops. Without this, you could click button 10
    // times real fast, and watch an animation of the info showing and closing
    // for a few seconds after
    icon.stop();
    info.stop();

    // Flip icon and hide/show info
    icon.toggleClass('flip');

    // Metnod 1, animation handled by JS
    // info.slideToggle('slow');

    // Method 2, animation handled by CSS, use with setInfoheight function
    info.toggleClass('active').height(icon.is('.flip') ? info.attr('h') : '0');

  });
};

여기에 이 옷의 스타일링입니다.info학급.

.info {
  display: inline-block;
  height: 0px;
  line-height: 1.5em;
  overflow: hidden;
  padding: 0 1em;
  transition: height 0.6s, padding 0.6s;
  &.active {
    border-bottom: $thin-line;
    padding: 1em;
  }
}

제 프로젝트 중 하나에서 이걸 사용했기 때문에 학급 이름이 구체적입니다.원하는 대로 변경할 수 있습니다.

크로스 브라우저에서는 스타일링이 지원되지 않을 수 있습니다.크롬에서는 잘 작동합니다.

아래는 이 코드에 대한 실제 예시입니다.클릭하기만 하면 됩니다.?애니메이션을 시작하는 아이콘

코드펜

자바스크립트가 없는 변형.CSS만.

CSS:

.toggle_block {
    border: 1px solid #ccc;
    text-align: left;
    background: #fff;
    overflow: hidden;
}
.toggle_block .toggle_flag {
    display: block;
    width: 1px;
    height: 1px;
    position: absolute;
    z-index: 0;
    left: -1000px;
}
.toggle_block .toggle_key {
    font-size: 16px;
    padding: 10px;
    cursor: pointer;
    -webkit-transition: all 300ms ease;
       -moz-transition: all 300ms ease;
        -ms-transition: all 300ms ease;
         -o-transition: all 300ms ease;
            transition: all 300ms ease;
}
.toggle_block .content {
    padding: 0 10px;
    overflow: hidden;
    max-height: 0;
    -webkit-transition: all 300ms ease;
       -moz-transition: all 300ms ease;
        -ms-transition: all 300ms ease;
         -o-transition: all 300ms ease;
            transition: all 300ms ease;
}
.toggle_block .content .toggle_close {
    cursor: pointer;
    font-size: 12px;
}
.toggle_block .toggle_flag:checked ~ .toggle_key {
    background: #dfd;
}
.toggle_block .toggle_flag:checked ~ .content {
    max-height: 1000px;
    padding: 10px 10px;
}

HTML:

<div class="toggle_block">
    <input type="checkbox" id="toggle_1" class="toggle_flag">
    <label for="toggle_1" class="toggle_key">clicker</label>
    <div class="content">
        Text 1<br>
        Text 2<br>
        <label for="toggle_1" class="toggle_close">close</label>
    </div>
</div>

다음 블록의 경우 html에서 ID 및 FOR 특성만 변경합니다.

CSS3로 쉽게 슬라이드업을 할 수 없기 때문에 JensT 스크립트를 자바스크립트 폴백과 콜백이 있는 플러그인으로 바꿨습니다.

만약 당신이 현대적인 브라우저를 가지고 있다면 당신은 css3 cs 전환을 사용할 수 있습니다.브라우저가 정상적으로 지원되지 않는 경우 이전 방식의 슬라이드 위로 슬라이드 아래로 이동합니다.

 /* css */
.csstransitions .mosneslide {
  -webkit-transition: height .4s ease-in-out;
  -moz-transition: height .4s ease-in-out;
  -ms-transition: height .4s ease-in-out;
  -o-transition: height .4s ease-in-out;
  transition: height .4s ease-in-out;
  max-height: 9999px;
  overflow: hidden;
  height: 0;
}

플러그인

(function ($) {
$.fn.mosne_slide = function (
    options) {
    // set default option values
    defaults = {
        delay: 750,
        before: function () {}, // before  callback
        after: function () {} // after callback;
    }
    // Extend default settings
    var settings = $.extend({},
        defaults, options);
    return this.each(function () {
        var $this = $(this);
        //on after
        settings.before.apply(
            $this);
        var height = $this.height();
        var width = $this.width();
        if (Modernizr.csstransitions) {
            // modern browsers
            if (height > 0) {
                $this.css(
                    'height',
                    '0')
                    .addClass(
                        "mosne_hidden"
                );
            } else {
                var clone =
                    $this.clone()
                    .css({
                        'position': 'absolute',
                        'visibility': 'hidden',
                        'height': 'auto',
                        'width': width
                    })
                    .addClass(
                        'mosne_slideClone'
                )
                    .appendTo(
                        'body'
                );
                var newHeight =
                    $(
                        ".mosne_slideClone"
                )
                    .height();
                $(
                    ".mosne_slideClone"
                )
                    .remove();
                $this.css(
                    'height',
                    newHeight +
                    'px')
                    .removeClass(
                        "mosne_hidden"
                );
            }
        } else {
            //fallback
            if ($this.is(
                ":visible"
            )) {
                $this.slideUp()
                    .addClass(
                        "mosne_hidden"
                );
            } else {
                $this.hide()
                    .slideDown()
                    .removeClass(
                        "mosne_hidden"
                );
            }
        }
        //on after
        setTimeout(function () {
            settings.after
                .apply(
                    $this
            );
        }, settings.delay);
    });
}
})(jQuery);;

사용방법

/* jQuery */
$(".mosneslide").mosne_slide({
    delay:400,
    before:function(){console.log("start");},
    after:function(){console.log("done");}
});

데모 페이지는 여기 http://www.mosne.it/playground/mosne_slide_up_down/ 에서 찾을 수 있습니다.

    try this for slide up slide down with animation 
give your **height

        @keyframes slide_up{
            from{
                min-height: 0;
                height: 0px;
                opacity: 0;
            }
            to{
                height: 560px;
                opacity: 1;
            }
        }

        @keyframes slide_down{
            from{
                height: 560px;
                opacity: 1;
            }
            to{
                min-height: 0;
                height: 0px;
                opacity: 0;
            } 
        }

언급URL : https://stackoverflow.com/questions/5072526/css3-equivalent-to-jquery-slideup-and-slidedown

반응형