IT story

Twitter 부트 스트랩을 사용하여 자동으로 경고를 닫는 방법

hot-time 2020. 9. 4. 08:09
반응형

Twitter 부트 스트랩을 사용하여 자동으로 경고를 닫는 방법


나는 트위터의 부트 스트랩 CSS 프레임 워크 (환상적이다)를 사용하고있다. 사용자에게 보내는 일부 메시지의 경우 Javascript JS 및 CSS 경고를 사용하여 표시하고 있습니다.

관심있는 사람들은 여기에서 찾을 수 있습니다 : http://getbootstrap.com/javascript/#alerts

내 문제는 이것입니다. 사용자에게 경고를 표시 한 후 일정 시간 간격이 지나면 사라지기를 원합니다. 트위터의 문서와 내가 살펴본 코드에 따르면 이것이 구워지지 않은 것처럼 보입니다.

  • 내 첫 번째 질문은 이것이 실제로 Bootstrap에 구워지지 않았는지 확인하는 요청입니다.
  • 둘째,이 동작을 어떻게 달성 할 수 있습니까?

부름 window.setTimeout(function, delay)을 통해이 작업을 수행 할 수 있습니다. 다음은 경고가 표시된 후 2 초 (또는 2000 밀리 초) 후에 자동으로 경고를 닫는 예입니다.

$(".alert-message").alert();
window.setTimeout(function() { $(".alert-message").alert('close'); }, 2000);

멋진 기능으로 감싸고 싶다면 이렇게 할 수 있습니다.

function createAutoClosingAlert(selector, delay) {
   var alert = $(selector).alert();
   window.setTimeout(function() { alert.alert('close') }, delay);
}

그러면 이렇게 사용할 수 있습니다 ...

createAutoClosingAlert(".alert-message", 2000);

나는 이것을 달성하는 더 우아한 방법이 있다고 확신합니다.


alert. ( 'close')에서도 작동하도록 만들 수 없습니다.

그러나 나는 이것을 사용하고 있으며 치료 효과가 있습니다! 경고는 5 초 후에 사라지고 사라지면 그 아래의 콘텐츠가 자연스러운 위치로 올라갑니다.

window.setTimeout(function() {
    $(".alert-message").fadeTo(500, 0).slideUp(500, function(){
        $(this).remove(); 
    });
}, 5000);

팝업 경고를 처리하고 페이딩하려고 할 때 이와 동일한 문제가 발생했습니다. 나는 여러 곳을 둘러 보았고 이것이 나의 해결책이라는 것을 알았다. 'in'클래스를 추가하고 제거하면 문제가 해결되었습니다.

window.setTimeout(function() { // hide alert message
    $("#alert_message").removeClass('in'); 

}, 5000);

.remove () 및 유사하게 .alert ( 'close') 솔루션을 사용할 때 문서에서 경고가 제거되는 문제가 발생한 것처럼 보였으므로 동일한 경고 div를 다시 사용하고 싶다면 할 수 없었습니다. 이 솔루션은 페이지를 새로 고치지 않고도 경고를 다시 사용할 수 있음을 의미합니다. (저는 aJax를 사용하여 양식을 제출하고 사용자에게 피드백을 제공했습니다)

    $('#Some_Button_Or_Event_Here').click(function () { // Show alert message
        $('#alert_message').addClass('in'); 
    });

경고에 대한 '닫기'작업을 사용하면 DOM에서 경고가 제거되고 경고가 여러 번 필요하기 때문에 작동하지 않습니다 (Ajax로 데이터를 게시하고 모든 게시물에서 사용자에게 메시지를 표시합니다). . 그래서 필요할 때마다 경고를 생성 한 다음 타이머를 시작하여 생성 된 경고를 닫는이 함수를 만들었습니다. 경고를 추가 할 컨테이너의 ID, 경고 유형 ( '성공', '위험'등) 및 메시지를 함수에 전달합니다. 내 코드는 다음과 같습니다.

function showAlert(containerId, alertType, message) {
    $("#" + containerId).append('<div class="alert alert-' + alertType + '" id="alert' + containerId + '">' + message + '</div>');
    $("#alert" + containerId).alert();
    window.setTimeout(function () { $("#alert" + containerId).alert('close'); }, 2000);
}

이것은 coffescript 버전입니다.

setTimeout ->
 $(".alert-dismissable").fadeTo(500, 0).slideUp(500, -> $(this.remove()))
,5000

위의 각 솔루션에서 경고의 재사용 가능성을 계속 잃었습니다. 내 솔루션은 다음과 같습니다.

페이지로드시

$("#success-alert").hide();

경고를 표시해야하는 경우

 $("#success-alert").show();
 window.setTimeout(function () {
     $("#success-alert").slideUp(500, function () {
          $("#success-alert").hide();
      });
 }, 5000);

fadeTo는 불투명도를 0으로 설정하므로 디스플레이가 없음이었고 불투명도가 0이어서 솔루션에서 제거했습니다.


After going over some of the answers here an in another thread, here's what I ended up with:

I created a function named showAlert() that would dynamically add an alert, with an optional type and closeDealy. So that you can, for example, add an alert of type danger (i.e., Bootstrap's alert-danger) that will close automatically after 5 seconds like so:

showAlert("Warning message", "danger", 5000);

To achieve that, add the following Javascript function:

function showAlert(message, type, closeDelay) {

    if ($("#alerts-container").length == 0) {
        // alerts-container does not exist, add it
        $("body")
            .append( $('<div id="alerts-container" style="position: fixed;
                width: 50%; left: 25%; top: 10%;">') );
    }

    // default to alert-info; other options include success, warning, danger
    type = type || "info";    

    // create the alert div
    var alert = $('<div class="alert alert-' + type + ' fade in">')
        .append(
            $('<button type="button" class="close" data-dismiss="alert">')
            .append("&times;")
        )
        .append(message);

    // add the alert div to top of alerts-container, use append() to add to bottom
    $("#alerts-container").prepend(alert);

    // if closeDelay was passed - set a timeout to close the alert
    if (closeDelay)
        window.setTimeout(function() { alert.alert("close") }, closeDelay);     
}

I needed a very simple solution to hide something after sometime and managed to get this to work:

In angular you can do this:

$timeout(self.hideError,2000);

Here is the function that i call when the timeout has been reached

 self.hideError = function(){
   self.HasError = false;
   self.ErrorMessage = '';
};

So now my dialog/ui can use those properties to hide elements.


With delay and fade :

setTimeout(function(){
    $(".alert").each(function(index){
        $(this).delay(200*index).fadeTo(1500,0).slideUp(500,function(){
            $(this).remove();
        });
    });
},2000);

try this one

$(function () {

 setTimeout(function () {
            if ($(".alert").is(":visible")){
                 //you may add animate.css class for fancy fadeout
                $(".alert").fadeOut("fast");
            }

        }, 3000)

});

참고URL : https://stackoverflow.com/questions/7643308/how-to-automatically-close-alerts-using-twitter-bootstrap

반응형