简体   繁体   中英

How can I use Javascript to center a drop down menu on a page?

I am using a third-party survey software (Qualtrics). I have a survey question, and the answer is a drop-down menu. You can see this at the bottom of the page at alsquest.org and in the image below.

屏幕截图

I want to center the drop down menu under the question text. (Failing that, another option would be to indent the drop-down menu so that it aligns with the rest of the text; I believe the current indent is 120px.)

I have access to the HTML for the question text, but the only way I can modify the answer drop-down menu is to use JavaScript. Qualtrics allows you to add JavaScript, but I am not a coder so I have no idea what code to use. This is the code shell that they provide for the JavaScript:

 Qualtrics.SurveyEngine.addOnload(function() { /*Place Your JavaScript Here*/ }); 

My question is, what JavaScript code do I put there to center (or indent) the drop-down menu? Any suggestions or questions would be appreciated.

To do this in JavaScript, you need to 'get' the HTML element from the page, and then set the CSS style. You could do it like this:

var dropDown = document.getElementById("the-dropdown");
dropDown.className = "dropdown-css-class";

Then in a CSS file included on the HTML page you would have to define the class:

.dropdown-css-class {
    margin-left: 120px;
}

or like this:

var dropDown = document.getElementById("the-dropdown");
dropDown.style["margin-left"] = "120px";

Without seeing the HTML I can only guess at how you would center or otherwise align the drop down, but this should get you going. You can experiment with jsfiddle .

I guess you can change css by jquery like this: First you need to find id or class of that dropdown menu. After that you can add jquery code to the code like this:

$("HERE GO ID OR CLASS FROM THAT ELEMENT").css("align","center");

or what ever you want for css.

But if you have more dropdown menus. You should get class and say

$("CLASS NAME").on('click', function(){

and here get id from clicked one and then use above code for changing css

});

This is best done with CSS. In your case, you can add the following code in the "Custom CSS" section of the Advanced Look and Feel Settings :

#QID2 > div.Inner.BorderColor.DL > div > fieldset > div {
    text-align: center !important;
}

Note that this will only work for that specific dropdown in that specific survey (Nothing else will be affected). If you change your survey theme it may no longer work for you so watch out for that.

As an FYI I worked in Qualtrics Support for a year.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM