通过Jquery更改CSS - 我的代码有什么问题

Change CSS via Jquery - What is wrong with my code?

本文关键字:代码 什么 问题 我的 Jquery 更改 CSS 通过      更新时间:2023-09-26

我正在尝试完成一个简单的函数,这段代码有什么问题?

基本上,我正在尝试覆盖一个跨度,其宽度与其包含<a>链接完全相同。所以我希望黑色跨度框(例如)与包含灰色框一样宽。

function vg() {
    if ($("body").hasClass("work-page")) {
        var a = $(".projTitle").width();
        $(".subtitle").css({
            width: a + "px",
        })
    }
li {
	position:relative;
}
li a.projTitle {
    display: inline-block;
    margin: auto 15px auto 0px;
    line-height: 100px;
    height: 100px;
    overflow: hidden;
    outline: 0;
    border: 0;
    font-weight:300;
    background:#ccc;
    font-size:18px;
}
li .subtitle {
    font-size:10px;
    font-family: 'Titillium Web', sans-serif;
    font-weight: 500;
    opacity: .8;
    display: block;
    margin-left: 0px;
    line-height: 17px;
    margin-right: 0px;
    height: 100px;
    margin-bottom: 0px;
    position: absolute;
    top: 0px;
    padding-top: 83px;
    width:auto;
    background:#000;
    color:#fff;
}
<html>
  <body class="work-page">
<ul>
  <li>
    <a class="css3Animate projTitle" href="work/project/index.html">The Project<span class="css3Animate subtitle">subtext span</span></a>
  </li>
  </body>
</html>

你需要调用该函数。您可以在脚本标记中调用它,而无需按照下面的注释中的建议在 html 中引用,最好将处理程序附加到脚本标记中而不是内联

$(".css3Animate").click(function(){
    vg();;
})

或者,您可以使用内联调用该函数onclick="vg()"

 <a class="css3Animate projTitle" href="#" onclick="vg()">The Project<span class="css3Animate subtitle">subtext span</span></a>

在这里看到 jsfiddle 与它一起工作

你有没有

调用这个函数?如果我打电话给我,对我有用vg()

function vg() {
	    if ($("body").hasClass("work-page")) {
        	var a = $(".projTitle").width();
          console.log(a)
	           		$(".subtitle").css({
                width: a + "px",
            	})
		}
    }
    
    vg()
li {
	position:relative;
}
li a.projTitle {
    display: inline-block;
    margin: auto 15px auto 0px;
    line-height: 100px;
    height: 100px;
    overflow: hidden;
    outline: 0;
    border: 0;
    font-weight:300;
    background:#ccc;
    font-size:18px;
}
li .subtitle {
    font-size:10px;
    font-family: 'Titillium Web', sans-serif;
    font-weight: 500;
    opacity: .8;
    display: block;
    margin-left: 0px;
    line-height: 17px;
    margin-right: 0px;
    height: 100px;
    margin-bottom: 0px;
    position: absolute;
    top: 0px;
    padding-top: 83px;
    width:auto;
    background:#000;
    color:#fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body class="work-page">
<ul>
  <li>
    <a class="css3Animate projTitle" href="work/project/index.html">The Project<span class="css3Animate subtitle">subtext span</span></a>
  </li>

我会对你使用的代码保持警惕。

例如,如果你有更多的元素与你选择的类相同,即projTitle,JQuery的.width()将获得数组的第一个元素,因为按类($(')选择一些东西。+className)) 将返回具有该类的元素数组。

就像您通过 ID 选择某些内容一样,因为没有任何东西应该共享 ID,您一定会得到正确的元素:)