【发布时间】:2021-01-29 07:02:10
【问题描述】:
我有一个非常简单的问题,但这是我以前没有做过的事情。
我的 HTML 中有 <span>↑</span>:
<div class="button--up-down" data-type="up">
<span>↑</span>
</div>
但我的 JS 中没有 <span>↑</span>:
var lastPageScroll = 0;
$(document).on('click', '.button--up-down', function () {
var type = $(this).attr('data-type');
var speed = 0; //ms
if (type == 'up') {
lastPageScroll = $("body,html").scrollTop();
if (lastPageScroll > 0) $(this).attr('data-type', 'down').text('↓');
$("body,html").animate({
scrollTop: 0
}, speed);
}
if (type == 'down') {
$(this).attr('data-type', 'up').text('↑');
$("body,html").animate({
scrollTop: lastPageScroll
}, speed);
}
});
$(document).on('scroll', function () {
var $button_up_down = $('.button--up-down');
var type = $button_up_down.attr('data-type');
if ($(window).scrollTop() > 150) {
$button_up_down.addClass("visible");
if (type == 'down') {
$button_up_down.attr('data-type', 'up').text('↑');
}
} else if (lastPageScroll == 0 || ($button_up_down.attr('data-type') == 'up' && $(window).scrollTop() < 150)) $button_up_down.removeClass("visible");
});
所以我需要在我的 JS 中添加 <span>↑</span>,但我不确定如何在不使用 innerHTML 的情况下添加它?
抱歉这个菜鸟问题。
【问题讨论】:
-
$("#somewhere").append("<span>↑</span>") -
代替这个:
$(this).attr('data-type', 'down').text('↓');,试试$(this).attr('data-type', 'down').find('span').text('↓');
标签: javascript html text