2016-03-10 3 views
0

Скрипки: https://jsfiddle.net/6avyo8zf/Как анимировать текст в правой

JQuery:

$(function() { 
    $(".content-box").hover(function() { 
     $(this).children("div:first-child").find(".hdrText").animate({ 'marginLeft': '+=100%' }, 2000); 
    }, function() { 
     $(this).children("div:first-child").find(".hdrText").animate({ 'marginLeft': '-=100%' }, 2000); 
    }); 
}); 

Как я могу изменить сценарий так, чтобы при наведении курсора мыши, текст одушевляет вправо, пока он не придет вправо черная рамка и выключение, текст возвращается в исходное положение.

+0

Для этого вам не нужен javascript – Luke

+0

Я использую IE9, и к этой цели, к сожалению. – Si8

+0

Это неудачно – Luke

ответ

1

Если содержимое не слишком динамично, как в изображении имеет фиксированный размер, вы можете использовать что-то вроде:

$(function() { 
    var hdr =$(".content-box").hover(function() {  
    hdr.stop().animate({left: $(this).parent().width() - hdr.width() - startoffset } , 2000); 
    }, function() { 
    hdr.stop().animate({left:0}, 2000); 
    }).find("div:first-child>.hdrText").css('position', 'relative'); 
    var startoffset = hdr.offset().left; 
}); 

Fiddle

положения relative необходим для анимации left и устанавливается здесь с помощью jquery, но также может быть установлен в css. .stop() является дополнительным дополнением, чтобы убедиться, что предыдущая анимация прекращена. например анимация влево все еще выполняется, когда наведение завершено.

+0

Спасибо. Я просто проверил «Скрипку» и, возможно, был тем, что мне нужно. Я буду тестировать в своем проекте и обновлять. – Si8

+0

Только один вопрос, если у меня есть несколько классов того же класса, как я могу гарантировать, что он нацелен только на ту, на которой я навис? – Si8

+0

Одним из способов было бы связать события наведения отдельно: https://jsfiddle.net/6avyo8zf/8/, этого было бы достаточно для целевого сценария? –

1

Вы можете сделать это только с помощью CSS, без необходимости в этом jQuery-коде. Это в основном работает, делая .hdrText изменение, когда .content-box зависает.

Демо:

.content-box { 
 
    position: relative; /* required for absolute positioning in children to work */ 
 
} 
 

 
.hdrText { 
 
    position: absolute; 
 
    top: 4px; 
 
    left: 44px; 
 
    right: 100%; /* allows us to animate the right offset */ 
 
    text-align: right; /* makes sure text does not overflow */ 
 
    transition: 2s; 
 
} 
 

 
.content-box:hover .hdrText { 
 
    right: 10px; /* animate right offset to 10px (gap from edge) 
 
}
<div style="width: 40%; overflow: hidden; float: left; border: 1px solid black;"> 
 
    <div class="content-box-blue content-box"> 
 
    <div class="title content-box-title"> 
 
     <div style="display: inline-block; width: 30px; height: 30px; vertical-align: middle; overflow: hidden; padding: 0 10px 0 0;"> 
 
     <img src="theimage.png" style="z-index: 5; display: inline-block; width: 30px; height: 30px; vertical-align: middle;" class="" alt="sd"> 
 
     </div> 
 
     <span class="hdrText">Announcements</span> 
 
    </div> 
 
    <div class="content">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It 
 
     has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop 
 
     publishing software like Aldus PageMaker including versions of Lorem Ipsum. </div> 
 
    </div> 
 
</div>

jsFiddle вилка: https://jsfiddle.net/azizn/7080u1a1/2/


Edit - JQuery Решение

Я просто понял, что вам нужна поддержка IE9. Поэтому в основном вместо анимации transition используйте функцию jQuery animate для перемещения текста. Вам нужно будет сохранить правила CSS, которые я добавил.

$(function() { 
 
    $(".content-box").hover(function() { 
 
    $(this).children("div:first-child").find(".hdrText").animate({ 
 
     'right': '10px' 
 
    }, 2000); 
 
    }, function() { 
 
    $(this).children("div:first-child").find(".hdrText").animate({ 
 
     'right': '100%' 
 
    }, 2000); 
 
    }); 
 
});
.content-box { 
 
    position: relative; /* required for absolute positioning in children to work */ 
 
} 
 

 
.hdrText { 
 
    position: absolute; 
 
    top: 4px; 
 
    left: 44px; 
 
    right: 100%; /* allows us to animate the right offset */ 
 
    text-align: right; /* makes sure text does not overflow */ 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div style="width: 40%; overflow: hidden; float: left; border: 1px solid black;"> 
 
    <div class="content-box-blue content-box"> 
 
    <div class="title content-box-title"> 
 
     <div style="display: inline-block; width: 30px; height: 30px; vertical-align: middle; overflow: hidden; padding: 0 10px 0 0;"> 
 
     <img src="theimage.png" style="z-index: 5; display: inline-block; width: 30px; height: 30px; vertical-align: middle;" class="" alt="sd"> 
 
     </div> 
 
     <span class="hdrText">Announcements</span> 
 
    </div> 
 
    <div class="content">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It 
 
     has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop 
 
     publishing software like Aldus PageMaker including versions of Lorem Ipsum. </div> 
 
    </div> 
 
</div>

jsFiddle demo

Я бы рекомендовал hoverIntent JQuery плагин, чтобы избежать стрельбы функцию так много раз, в то время как анимация все еще работает ..

+0

Я бы хотел, чтобы JQuery-версия работала с IE9. jsfiddle.net/6avyo8zf/1, но он просто продолжает двигаться и не возвращается к исходной позиции мыши. – Si8

+0

@ SiKni8 обновлен решением jQuery, сообщите мне, если бы это сработало для вас. – Aziz

0

Сначала вам нужно чтобы добавить границу поля для смещения поля, добавляемого в левую сторону. Это создаст впечатление перемещения текста без изменения размера или перемещения страницы. Вы хотите этот негатив равного количества:

{'marginLeft': '+=100%', 'marginRight': '-=100%'} 

Я также заметил, анимация получает нервную, когда быстро носился над. Вы можете посмотреть в MouseEnter и MouseLeave для тех, а также добавления стоп() перед вашим одушевленным, чтобы отменить предыдущую анимацию:

https://api.jquery.com/mouseenter/

https://api.jquery.com/stop/

+0

https://jsfiddle.net/6avyo8zf/1/, но он просто продолжает двигаться и не возвращается к исходной позиции мыши. – Si8

1

Если вы хотите чистый поддержку JQuery вы можете сделать вам просто нужно вычислить точные пропорции для добавления и вычитания с учетом всех остальных элементов.

$(function() { 
    // Load all needed elements 
    var content = $(".content-box"); 
    var contentTitle = $(".content-box-title"); 
    var text = content.children("div:first-child").find(".hdrText"); 
    var theimage = $('#theimage'); 
    var currentAnimate = null; 
    content.hover(function() { 
     // Get titles total width 
     var contentWidth = contentTitle.width(); 
     // Get the texts total width 
     var textWidth = text.width(); 
     // Get the images total width 
     var theimageWidth = theimage.width(); 
     // Get the padding on the image 
     var imageParentPadding = theimage.parent().css('padding-right'); 
     // Add text, image and padding + 5 to accommodate changing screen size together so we can subtract that from content width 
     var subtractWidth = textWidth + theimageWidth + parseInt(imageParentPadding) + 5; 
     // Save value to move back to same position in case screen size changes between animations 
     currentAnimate = contentWidth - subtractWidth; 
     // Animate margin left by the total content width minus the width of all the other elements and paddings 
     text.animate({ 
      'marginLeft': '+=' + currentAnimate 
     }, 2000); 
    }, function() { 
     text.animate({ 
      'marginLeft': '-=' + currentAnimate 
     }, 2000); 
    }); 
}); 

Fiddle: https://jsfiddle.net/6avyo8zf/7/

Смежные вопросы