Transitioning from right to left
我有一个网站,需要在其中从屏幕右侧向左侧移动一些文本。文本的长度不断变化,所以我不能仅仅硬编码一个宽度来实现我想要的。
我尝试进行过渡,但是当我从右向左移动时,它将停止工作。我已经写了一个简单的jsfiddle来演示我的问题以及如何解决这个问题。第一个div展示了它应该如何工作,但是我需要文本向左对齐而不是向右对齐(text-align属性不适用于我的完整代码)。第二个div向您显示当我向左过渡时发生的实际结果。
https://jsfiddle.net/h12wrm1n/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | $("#right").on("click", function () { $("#right").toggleClass("active"); }); $("#right2").on("click", function () { $("#right2").toggleClass("active"); }); .right, .right2{ width: 300px; position: absolute; right: 20px; transition: .5s } .right2{ top: 100px; } .right.active{ right: 200px; } .right2.active{ left: 20px } This is some text This is some text |
如果我不知道文本的宽度,如何从右向左过渡?另外请记住,页面是响应式的。
一种可能性是使用容器容纳带有文本的元素。并转换容器和内部元素。
有关详细信息,请参见代码段。悬停在身体??上将触发变换。我已经在容器上设置了颜色,以使其更容易看到正在发生的事情
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | body { width: 300px; border: solid 1px red; margin: 30px; } .container { width: 100%; background-color: lightblue; transform: translateX(100%); } .test { display: inline-block; transform: translateX(-100%); } body:hover .container { transform: translateX(0%); } body:hover .test { transform: translateX(0%); } .container, .test { transition: transform 1s; } |
1 2 3 4 | Text longer.............. text |
不能通过不同的属性过渡(
仅
因此,您的第二个元素应仅通过
最初将元素设置为
的假正确位置
1 2 | +-----------------------------------+ | ##|############# |
1 2 | +-----------------------------------+ | ############### | |
1 2 | +-----------------------------------+ | ############### | |
示例
1 2 3 | $("#right, #right2").on("click", function () { $(this).toggleClass("active"); }); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #right, #right2{ position: absolute; background: #f0f; transition: 0.5s; } #right {right: 20px; } #right.active{right: 200px;} #right2{ display: table; top: 50px; left: calc(100% - 20px); transform: translateX(-100%); } #right2.active{ left: 20px; transform: translateX(0%); } |
1 2 3 | <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> click to animate right200px click to animate left20px (some long text here) |
执行此操作的一种可能方法是计算文本的宽度,然后从设备的宽度中减去
然后动画以从左0到左的绝对位置=
我相信还有更好的方法。 :)