gpt4 book ai didi

javascript - 无法从显示为 : flex 的父 div 获取 "left"值

转载 作者:行者123 更新时间:2023-12-04 08:38:39 25 4
gpt4 key购买 nike

所以我试图在单击按钮时制作背景幻灯片动画,但我似乎无法从下面的代码中获得“左”的确切值,显然我在这里做错了什么......
我试图使“.btn”位置:静态/相对,两者都导致“左”=“自动”或“0”。
试过偏移(),位置(),对我不起作用。任何帮助都感激不尽!

$(".btn").click(function(){
var pos_left = $(this).css("left");
$(".result").html(pos_left);
//$(".animation").css("left", pos_left); (THIS IS EXPECTED)
$(".animation").css("left", 35);
});
.wrapper {
position: relative;
}

.container {
display: flex;
width: min-content;
justify-content: center;
background: rgba(255, 255, 255, 0);
border: 2px black solid;
}
.btn {
background-color: rgba(255, 255, 255, 0);
color: green;
max-width: 110px;
width: 100%;
height: 30px;
font-size: 12px;
border: 2px green solid;
border-color: yellowgreen;
white-space: nowrap;
}

.animation {
position: absolute;
top: 0px;
left: 0px;
height: 100%;
width: 34px;
background: red;
z-index: -1;
transition: 0.4s;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="wrapper">
<div class="container">
<div class="btn">Box 1</div>
<div class="btn">Box 2</div>
<div class="btn">Boxie 3</div>
<div class="btn">Boxie box 4</div>
</div>
<div class="animation"></div>
</div>
<div class="result"></div>

最佳答案

我只是尝试让您的代码尽可能天真地工作,如下所示:

$(".btn").click(function(){
var position = $(this).position();
var pos_left = position.left;
var elementWith = $(this).outerWidth();
$(".result").html(pos_left);
$(".animation").css("left", pos_left);
$(".animation").width(elementWith)
});
.wrapper {
position: relative;
}

.container {
display: flex;
width: min-content;
justify-content: center;
background: rgba(255, 255, 255, 0);
border: 2px black solid;
}
.btn {
background-color: rgba(255, 255, 255, 0);
color: green;
max-width: 110px;
width: 100%;
height: 30px;
font-size: 12px;
border: 2px green solid;
border-color: yellowgreen;
white-space: nowrap;
}

.animation {
position: absolute;
top: 0px;
left: 0px;
height: 100%;
width: 34px;
background: red;
z-index: -1;
transition: 0.4s;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="wrapper">
<div class="container">
<div class="btn">Box 1</div>
<div class="btn">Box 2</div>
<div class="btn">Boxie 3</div>
<div class="btn">Boxie box 4</div>
</div>
<div class="animation"></div>
</div>
<div class="result"></div>

关于javascript - 无法从显示为 : flex 的父 div 获取 "left"值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64669379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com